如何解决包含在布局PHP中的变量的可见性问题
编辑: 根据问题:Reference: What is variable scope,which variables are accessible from where and what are “undefined variable” errors? 应该为我工作,但不是。我可能听不懂,但看不到错误在哪里。
我是PHP的新手,所以问题可能很简单又很愚蠢。我有3个文件:index.php
,View.php
和layout.php
。在View php
中,我有一个View类定义和一个render()
方法。除其他方法外,此方法还包括文件layout.php
中的HTML模板。
但是:在<main>
标记的PHP文件中,我有一段php代码(if
语句),该代码取决于$page
变量的值(在PHP文件),包括其他文件
问题在于此变量在layout.php
文件中显示为未定义。
我不明白为什么,最终所有代码都在index.php
中执行:包括View类,而render函数包括layout.php
。
请帮助我理解这一点,因为我做不到。预先感谢。
注意:未定义的变量:第17行的C:\ xampp \ htdocs \ notes \ templates \ layout.php中的操作
index.php
<?php
declare(strict_types=1);
namespace App;
require_once("src/utils/debug.php");
require_once("src/View.php");
$action = $_GET['action'] ?? null;
$view = new View();
$view -> render($action );
View.php
<?php
declare(strict_types=1);
namespace App;
class View
{
public function render(?string $page): void
{
include_once("templates/layout.php");
}
}
layout.php
<html>
<head>
</head>
<body>
<header>
<h1>Nagłówek</h1>
</header>
<nav>
<ul>
<li><a href="index.php/?action=list">Lista notatek</li>
<li><a href="index.php/?action=create">Nowa notatka</li>
</ul>
</nav>
<main>
<?php
if ($page === 'create') {
include_once("templates/pages/list.php");
} else {
include_once("templates/pages/create.php");
}
?>
</main>
<footer>
</footer>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。