简体   繁体   中英

global inside and outside a function in PHP?

I usually run code like this just fine:

$ZANE_REGISTER_RULES='this wont print';
myTest();

function myTest()
    {
    **global $ZANE_REGISTER_RULES**;
    $ZANE_REGISTER_RULES='this will actually print';
    }

echo $ZANE_REGISTER_RULES; //will print "this will actually print"

But sometime (eg: if I put this inside a phpBB page) this doesn't work (the echo says "this wont print") unless I declare the variable global the first time too:

**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='my rulessssssssssssssss';
myTest();

function myTest()
    {
    **global $ZANE_REGISTER_RULES**;
    $ZANE_REGISTER_RULES='funziona';
    }

echo $ZANE_REGISTER_RULES; //will print "this will actually print"

I'm pretty sure that the first way is the correct one and the second one just doesn't mean anything, nevertheless the second one works, the first one doesn't.

PLEASE don't waste time replying "global are bad programming" because this is not the issue at hand, neither "why would you do such a thing?" because this is obviusly an example.

There is only one reason why this might be happening: the code in the second example is being compiled in the context of a function. That's why $ZANE_REGISTER_RULES has local scope by default.

If there is no enclosing function in the source file where the code itself appears, this means that the file is being included by some other file inside a function context, for example:

var_access.php

echo "Hello ".$name."\n"; 
echo "Hello ".$_GLOBALS['name']."\n"; 

test_1.php

// Here var_access.php is included in the global context
$name = 'world';
include('var_access.php'); // Prints "Hello world" twice

test_2.php

// Here var_access.php is included in a function context
$name = 'world';
function func() {
    $name = 'function world';
    include('var_access.php'); // Prints "Hello world" and "Hello function world"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM