it appears to be failing for several reasons. i have commented it and provided 2 ways you can fix it.
your way
<?php
// Test program
foo();
function foo() {
global $x; //doesnt exist
$y = 42; //local variable
$x =& $y; //x is pointer to local y
print "x=$x\n"; //42
print "y=$y\n"; //42
bar();
}
function bar() {
global $x; //no global x, foo is not global
print "x=$x\n"; //nothing
}
?>
the first call to global $x in foo doesnt do anything since there is no global var $x. calling global $x is a simpler and cleaner way of doing
function foo(&$x) {
then you create a var local to foo, create a new var x which is a pointer to local y. bar has no idea they exist (x or y)
one fix
<?php
// Test program
$y = 0; //create global y
foo();
function foo() {
global $y; //bring in y
$y = 42; //set it
$x =& $y; //local x pointer to glob y
print "x=$x\n"; //42
print "y=$y\n"; //42
bar();
}
function bar() {
global $y; //bring in glob y, set as 42
print "y=$y\n"; //42
}
?>
in this way, you just have to change the variable you use. y is defined in the global scope so it exists to all functions and lasts for the lifetime of the program
other way
<?php
// Test program
foo();
function foo() {
$y = 42; //set local y = 42
$x =& $y; //local x pointer to y
print "x=$x\n"; //42
print "y=$y\n"; //42
bar($x); //pass local x to bar
}
function bar(&$x) { //takes addr of x
print "x=$x\n"; //42
//since bar exists in foo, the variable $y in foo isnt destroyed yet so x still points to it. &$x = &$y
}
?>
no global variables, all exist locally to functions, but we explicitly pass the addr of x into bar before it is destroyed and it will result in what you want.