为什么我不能按值分配 $this,显然它总是按引用分配?
Why I cannot assign $this by value, it aparently is assigned by reference always?
下面的代码解释了我遇到的问题,我试图按值将 $this
赋给一个变量,但显然它最终是通过引用赋值的,为什么?我该怎么做?
下面的脚本是两个类Test
和TestQuery
的一组。 Test
假定 $num
属性中的值,然后脚本调用 Test->exist()
,创建两个变量:$original
"by value" 和 $obj
通过引用,在这一点上两者是一样的。最后脚本调用 TestQuery->doit( $obj )
;如果$num
的值为2,假设TestQuery
会修改$obj
的$code
,但是结果无效,因为$original
的值和exist()
中的$obj
新方法是一样的。
<?php
class TestQuery{
public function doit( &$obj )
{
if ($obj->getNum() == 2)
$obj->setCode( 55 );
}
}
class Test {
public $code;
public $num;
public function setCode( $code ) { $this->code= $code; }
public function getCode( $code ) { return $this->code; }
public function getNum()
{
return $this->num;
}
public function exist()
{
$original = $this;
$obj =& $this;
// The same objects ...(valid)
echo "<xmp>";
print_r( $original );
echo " VS ";
print_r( $obj );
echo "</xmp>";
$tc = new TestQuery();
$tc->doit( $obj );
// The same objects newly... (invalid, hoping different)
echo "<xmp>";
print_r( $original );
echo " VS ";
print_r( $obj );
echo "</xmp>";
}
}
$t = new Test();
$t->num = 2;
$t->exist();
exit;
?>
我找到的解决方案是使用 clone
关键字。
$original = clone $this;
下面的代码解释了我遇到的问题,我试图按值将 $this
赋给一个变量,但显然它最终是通过引用赋值的,为什么?我该怎么做?
下面的脚本是两个类Test
和TestQuery
的一组。 Test
假定 $num
属性中的值,然后脚本调用 Test->exist()
,创建两个变量:$original
"by value" 和 $obj
通过引用,在这一点上两者是一样的。最后脚本调用 TestQuery->doit( $obj )
;如果$num
的值为2,假设TestQuery
会修改$obj
的$code
,但是结果无效,因为$original
的值和exist()
中的$obj
新方法是一样的。
<?php
class TestQuery{
public function doit( &$obj )
{
if ($obj->getNum() == 2)
$obj->setCode( 55 );
}
}
class Test {
public $code;
public $num;
public function setCode( $code ) { $this->code= $code; }
public function getCode( $code ) { return $this->code; }
public function getNum()
{
return $this->num;
}
public function exist()
{
$original = $this;
$obj =& $this;
// The same objects ...(valid)
echo "<xmp>";
print_r( $original );
echo " VS ";
print_r( $obj );
echo "</xmp>";
$tc = new TestQuery();
$tc->doit( $obj );
// The same objects newly... (invalid, hoping different)
echo "<xmp>";
print_r( $original );
echo " VS ";
print_r( $obj );
echo "</xmp>";
}
}
$t = new Test();
$t->num = 2;
$t->exist();
exit;
?>
我找到的解决方案是使用 clone
关键字。
$original = clone $this;