0

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>
kmoser
  • 8,780
  • 3
  • 24
  • 40
Michal
  • 3
  • 3
  • `$action` is in the global scope, but functions and methods do not have global scope. You need to add the action as an argument to method `render` – whitelined Aug 19 '20 at 19:37
  • I did it. From my index.php file: $action = $_GET['action'] ?? null; $view = new View(); $view -> render($action ); – Michal Aug 19 '20 at 19:44
  • @whitelined Even if i add a line: $action = $page inside of render function, it sill dosent work – Michal Aug 19 '20 at 19:54
  • update your question to the new code, and I'll try and figure how to solve it. – whitelined Aug 19 '20 at 22:19
  • Now that you've updated your code, assuming it's still not working, what does the error message say? – Phil Aug 24 '20 at 02:34

0 Answers0