...

View Full Version : why doesnt this variable become global



kevinkhan
09-14-2011, 10:27 PM
ok iv set up a simple demo

this is the code im running


include('simple_html_dom.php');
include('config.php');
include('connect.php');
include('functions.php');
include($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'globalFunctions.php');

test();

echo "test variable = ".$test;

exit;

this is the function which is in globalFunctions.php which is two directories back ../../


function test() {
$test = 10;

global $test;
}

how come when i run script i am not getting variable echoed

Fou-Lu
09-15-2011, 12:27 AM
Because you cannot promote a variable to a global, you can only load one. $test as defined in main() would be a global one (that is, anywhere in the scope of the main running script; PHP's dummy main is not declarable as such). If $test does not reside in the symbols table, it will create it with a null value.



function test()
{
$test = 10;
// test::$test is declared with a value of 10.
global $test;
// test::$test is declared with a value of main::&$test
}

test();
print $test; // void.


global (which you should not ever use except in a situation where a callback cannot accept a modified function signature), must be declared BEFORE the local function variable in order to change. The example above loads the $test no problem, but since its already void it overwrites the local $test with the reference of the main's $test.

kevinkhan
09-15-2011, 09:36 AM
Because you cannot promote a variable to a global, you can only load one. $test as defined in main() would be a global one (that is, anywhere in the scope of the main running script; PHP's dummy main is not declarable as such). If $test does not reside in the symbols table, it will create it with a null value.



function test()
{
$test = 10;
// test::$test is declared with a value of 10.
global $test;
// test::$test is declared with a value of main::&$test
}

test();
print $test; // void.


global (which you should not ever use except in a situation where a callback cannot accept a modified function signature), must be declared BEFORE the local function variable in order to change. The example above loads the $test no problem, but since its already void it overwrites the local $test with the reference of the main's $test.


Ok Thanks for your help



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum