Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5 - Variable scope across include files with no classes or functions

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.

like image 541
user762985 Avatar asked May 20 '11 15:05

user762985


People also ask

What are the 4 variable scopes of PHP?

Summary. PHP has four types of variable scopes including local, global, static, and function parameters.

What is variable in PHP explain with its scope with example?

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.

What are the three different PHP variable scopes?

PHP has three types of variable scopes: Local variable. Global variable. Static variable.

What is the default scope of any variable and function in PHP?

Any variable used inside a function is by default limited to the local function scope.


1 Answers

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.

like image 92
Kev Avatar answered Oct 06 '22 01:10

Kev