This is the way how we use pointer to access variable inside the class. <?php classtalker{ private$data = 'Hi'; publicfunction & get(){ return$this->data; } publicfunctionout(){ echo$this->data; } } $aa = newtalker(); $d = &$aa->get(); $aa->out(); $d = 'How'; $aa->out(); $d = 'Are'; $aa->out(); $d = 'You'; $aa->out(); ?> the output is "HiHowAreYou"
Only Created $barand printing $bar my nameis"bar"and I live in"foo".
Now $bazis referenced to$barand printing $barand$baz my nameis"bar"and I live in"foo".
Now Creating MasterOne and Two and passing $barto both constructors Master: MasterOne | foo: my nameis"bar"and I live in"foo".
Master: MasterTwo | foo: my nameis"bar"and I live in"foo".
Now changing valueof$barand printing $barand$baz my nameis"baz"and I live in"foo". my nameis"baz"and I live in"foo".
Now printing again MasterOne and Two Master: MasterOne | foo: my nameis"baz"and I live in"foo".
Master: MasterTwo | foo: my nameis"baz"and I live in"foo".
Now changing MasterTwo's foo name and printing again MasterOne and Two Master: MasterOne | foo: my name is "MasterTwo's Foo" and I live in "foo". Master: MasterTwo | foo: my name is "MasterTwo's Foo" and I live in "foo". Also printing $bar and $baz my name is "MasterTwo's Foo" and I live in "foo". my name is "MasterTwo's Foo" and I live in "foo".
上个例子解析: $bar = new foo(‘bar’); $m1 = new MasterOne( $bar ); $m2 = new MasterTwo( $bar );
当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。也就是说和这样做是相同的:
1 2 3
<?php $var =& $GLOBALS["var"]; ?>
这意味着,例如,unset $var 不会 unset 全局变量。
如果在一个函数内部给一个声明为 global 的变量赋于一个引用,该引用只在函数内部可见。可以通过使用 $GLOBALS 数组避免这一点。
Example 在函数内引用全局变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php $var1 = "Example variable"; $var2 = "";
functionglobal_references($use_globals) { global$var1, $var2; if (!$use_globals) { $var2 =& $var1; // visible only inside the function } else { $GLOBALS["var2"] =& $var1; // visible also in global context } }
global_references(false); echo"var2 is set to '$var2'\n"; // var2 is set to '' global_references(true); echo"var2 is set to '$var2'\n"; // var2 is set to 'Example variable' ?>
把 global $var; 当成是 $var =& $GLOBALS[‘var’]; 的简写。从而将其它引用赋给 $var 只改变了本地变量的引用。