在PHP 5中,$ obj1 = $ obj2与$ obj1 =& $ obj2的

问题描述:

似乎在PHP 5中,$ obj1 = $ obj2与$ obj1 =& $ obj2


虽然手册说...

http://www.php.net/manual/en/languag...assignment.php

seems like in PHP 5, $obj1 = $obj2 is not the same as $obj1 =& $obj2

although the manual says...

http://www.php.net/manual/en/languag...assignment.php


从PHP 4开始,支持按引用分配,

使用$ var =& $ othervar
Since PHP 4, assignment by reference has been supported,
using the $var = &$othervar


从PHP 5起,对象通过引用分配

,除非明确告知新的克隆

关键字。
As of PHP 5, objects are assigned by reference
unless explicitly told otherwise with the new clone
keyword.



但是,$ obj1 = $ obj2

和$ obj1 =& $ obj2是两回事...


第一个是按参考分配

第二个是按同义词分配


- --------------- assign1.php ---------------------


<?php


class Foo {

var $ name;


function Foo($ i) {

$ this-> name ="我是$ i!\ n&quot ;;

}

}


$ a = new Foo(ha);

$ b = $ a;

$ b = new Foo( hee);


echo" This is php",phpversion()," \ n\\\
";

print_r ($ a);

print_r($ b);


?>


---- -------------输出


这是php 5.2.4


Foo对象



[姓名] =我是哈!




Foo对象



[姓名] =我是嘿!




--------- -------- assign2.php ---------------------


<?php


class Foo {

var $ name;


function Foo($ i){

$ this-> name ="我是$ i!\ n&quot ;;

}

}


$ a = new Foo(ha);

$ b =& $ a;

$ b = new Foo(hee) ;


echo"这是php",phpversion()," \ n \ n";

print_r($ a);

print_r($ b);


?>


--------- --------输出


这是php 5.2.4

Foo对象



[名字] =我是嘻嘻!




Foo对象



[姓名] =我是嘿!




However, $obj1 = $obj2
and $obj1 = &$obj2 are two different things...

the first one is "assignment by reference"
the second one is "assignment by synonym"

----------------- assign1.php ---------------------

<?php

class Foo {
var $name;

function Foo($i) {
$this->name = "I''m $i!\n";
}
}

$a = new Foo("ha");
$b = $a;
$b = new Foo("hee");

echo "This is php ", phpversion(), "\n\n";
print_r($a);
print_r($b);

?>

----------------- output

This is php 5.2.4

Foo Object
(
[name] =I''m ha!

)
Foo Object
(
[name] =I''m hee!

)
----------------- assign2.php ---------------------

<?php

class Foo {
var $name;

function Foo($i) {
$this->name = "I''m $i!\n";
}
}

$a = new Foo("ha");
$b = &$a;
$b = new Foo("hee");

echo "This is php ", phpversion(), "\n\n";
print_r($a);
print_r($b);

?>

----------------- output

This is php 5.2.4

Foo Object
(
[name] =I''m hee!

)
Foo Object
(
[name] =I''m hee!

)

obj1 =


obj2与

不一样

obj1 =&
obj1 =&