EDIT: According to the question: Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors? should work for me, but it does not. I probably don't understand something, but I can't see where the bug is.
I'm a newbie in PHP so the question is probably simple and stupid. I have 3 files: index.php
, View.php
and layout.php
. In View php
I have a View class definition and a render()
method. Among others, this method includes an HTML template from the file layout.php
.
But: in the PHP file in the <main>
tag I have a piece of php code (if
statement) which, depending on the value of the $page
variable (defined in the PHP file), includes a different file
The problem is that this variable appears as undefined in the layout.php
file.
I don't understand why, in the end all code is executed in index.php
: View class is included and render function includes layout.php
.
Please help me understand this, because I can't do it. Thanks in advance.
Notice: Undefined variable: action in C:\xampp\htdocs\notes\templates\layout.php on line 17
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>