<?php class Example { var $value = "some value"; function PrintValue() { print $this->value; } } $obj = new Example(); $obj->PrintValue(); ?> <?php function PrintValue($arr) { print $arr["value"]; } function CreateExample() { $arr["value"] = "some value"; $arr["PrintValue"] = "PrintValue"; return $arr; } $arr = CreateExample(); //Use PHP's indirect reference $arr["PrintValue"]($arr); ?> <?php $a = 5; //$b points to the same place in memory as $a $b与$a指向内存中同个地址 $b = &$a; //we're changing $b, since $a is pointing to 改变$b,指向的地址改变 //the same place - it changes too $a指向的地址也改变 $b = 7; //prints 7 输出7 print $a; ?>
1 class MyFoo { 2 function MyFoo() 3 { 4 $this->me = &$this; 5 $this->value = 5; 6 } 7 8 function setValue($val) 9 { 10 $this->value = $val; 11 } 12 13 function getValue() 14 { 15 return $this->value; 16 } 17 18 function getValueFromMe() 19 { 20 return $this->me->value; 21 } 22 } 23 24 function CreateObject($class_type) 25 { 26 switch ($class_type) { 27 case "foo": 28 $obj = new MyFoo(); 29 break; 30 case "bar": 31 $obj = new MyBar(); 32 break; 33 } 34 return $obj; 35 } 36 37 $global_obj = CreateObject ("foo"); 38 $global_obj->setValue(7); 39 40 print "Value is " . $global_obj->getValue() . "\n"; 41 print "Value is " . $global_obj->getValueFromMe() . "\n"; 1 class MyFoo { 2 function MyFoo() 3 { 4 $this->me = &$this; 5 $this->value = 2; 6 } 7 8 function setValue($val) 9 { 10 $this->value = $val; 11 } 12 13 function getValue() 14 { 15 return $this->value; 16 } 17 18 function getValueFromMe() 19 { 20 return $this->me->value; 21 } 22 }; 23 24 function &CreateObject($class_type) 25 { 26 switch ($class_type) { 27 case "foo": 28 $obj =& new MyFoo(); 29 break; 30 case "bar": 31 $obj =& new MyBar(); 32 break; 33 } 34 return $obj; 35 } 36 37 $global_obj =& CreateObject ("foo"); 38 $global_obj->setValue(7); 39 40 print "Value is " . $global_obj->getValue() . "\n"; 41 print "Value is " . $global_obj->getValueFromMe() . "\n"; ……