I've read through many, many threads on this and still can't wrap my head around it.
Here's my basic issue:
header.php
includes a file called navigation.php
. Within navigation.php
, $previous
and $next
are defined. Using echo statements I have verified they have values.
Next, header.php
includes a file called backnext.php
. I need backnext.php
to know the values of $previous
and $next
. If I declare them as global
at the top of backnext.php
, I don't get errors, but echo
statements show they are empty. If I don't, I get an undefined variable
error.
Where exactly do I need to declare them as global
to have backnext.php
be able to read their values correctly?
None of these files are using functions or classes.
Summary. PHP has four types of variable scopes including local, global, static, and function parameters.
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local.
PHP has three types of variable scopes: Local variable. Global variable. Static variable.
Any variable used inside a function is by default limited to the local function scope.
If none of these files have functions or classes then $prev
and $next
are in the global scope and should be seen by all your include files and you shouldn't need to use the global
keyword.
It sounds like the order of your includes may be a bit wrong.
Update:
If I understand correctly you have something like this:
header.php:
<?php
echo "In header.php\n";
require_once("navigation.php");
require_once("backnext.php");
echo "Also seen in header.php:\n";
echo "prev=$prev\n";
echo "next=$next\n";
?>
navigation.php:
<?php
echo "In navigation.php\n";
$prev = "Hello World#1";
$next = "Hello World#2";
echo "Exiting navigation.php\n";
?>
backnext.php:
<?php
echo "In backnext.php\n";
echo "prev=$prev\n";
echo "next=$next\n";
echo "Exiting backnext.php\n";
?>
If I run this I get:
In header.php In navigation.php Exiting navigation.php In backnext.php prev=Hello World#1 next=Hello World#2 Exiting backnext.php Also seen in header.ph prev=Hello World#1 next=Hello World#2
backnext.php
is able to see both $prev
and $next
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With