I'm trying to get a global var to show up in an included file. I'll replicate the path here:
$var = array();
funcA
{
global $var;
$var = array('some'=>'values');
funcB
{
global $var;
//$var prints('some'=>'values')
include_once('myfile.php');
}
}
OR
funcA
{
$var = array('some'=>'values');
funcB($var)
{
//$var prints('some'=>'values')
include_once('myfile.php');
}
}
myfile.php:
//prints own content (is included)
//$var is empty, whether declared global or not.
Am I missing a step?
EDIT: Before the upvote train of 'not using global variables' leaves me without an actual answer, the above still does not work even when $var
is passed as a parameter from funcA
to funcB
. I have edited the code to demonstrate.
The file is included via file path, not url, but does reside in another directory - is that relevant?
EDIT: Even when initialising a variable just before including the file, the value is not passed to that file. The issue seems to be in the include method itself. I'm using include_once()
and providing the full absolute path to the file.
Why not pass as a parameter and/or use return values? Your application shouldn't need to reply on globals, and is usually a sign of a design flaw.
function getVar() {
return array('some'=>'values');
}
function printVar($var) {
include_once('myfile.php');
// print_r($var);
}
$var = getVar();
printVar($var);
If your problem is larger than the example shows, you should take a look at PHP's OOP and start using classes/objects. Check out some frameworks to help you dive right in too.