kevinkhan Posted September 14, 2011 Share Posted September 14, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/247147-why-doesnt-this-variable-become-global/ Share on other sites More sharing options...
btherl Posted September 14, 2011 Share Posted September 14, 2011 What's happening there is you are setting a local $test to 10, then it gets overwritten when you do "global $test;". Declaring a variable global will actually overwrite any local copy you had in that function. If you set the value after declaring it global then it'll work as you expect. Quote Link to comment https://forums.phpfreaks.com/topic/247147-why-doesnt-this-variable-become-global/#findComment-1269371 Share on other sites More sharing options...
AbraCadaver Posted September 15, 2011 Share Posted September 15, 2011 I would get out of the habit of using global vars, but if you must, I would use: $GLOBALS['test'] = 10; Quote Link to comment https://forums.phpfreaks.com/topic/247147-why-doesnt-this-variable-become-global/#findComment-1269430 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.