Skip to content
Advertisement

Can’t access variable from an included php script

I am trying to access a variable $defaultPath from the php script that I have included.

However, when i am trying to echo the variable there is an error stating

undefined variable

. The php script is basically a nav bar (let’s call it navbar.php) and this includes the helper.php which is where the variable $defaultPath is located. Moreover, the navbar.php is included in index.php in which index.php also includes helper.php. I used include_once to include the helper.php in both navbar.php and index.php but only index.php can echo the variable but not navbar.php

Here are the codes: Navbar.php

JavaScript

Helper.php

JavaScript

Index.php

JavaScript

* What I have tried * I tried changing it back to include but error occurs because of duplicate functions.

I also tried echo-ing the the $defaultPath variable in index.php and there are no undefined error but when i try to do it in navbar.php it gives me undefined sadly

Note: I am not trying to access the variable inside a function scope

Advertisement

Answer

The execution is:

JavaScript

helper.php has thereby been included once.

JavaScript

This establishes a new function scope.

JavaScript

Includes the header which includes the navbar, all within the scope of subview.

JavaScript

Doesn’t do anything, since helper.php has already been included previously.

JavaScript

Tries to echo a variable which is not in scope and hasn’t been included.

Functions aren’t scoped; if the file which defines the function has been included once anywhere, they’re available globally everywhere. In fact, if you would try to include the file again, you’d run into an error about trying to redefine existing functions. That’s exactly what include_once is for, to avoid that problem.

You could use the global keyword to access your globally included and defined variable, or you could rethink your file structure to separate define-once functions from variables which need to be included multiple times.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement