【发布时间】:2017-03-04 10:56:18
【问题描述】:
下面的代码解释了我遇到的问题,我试图通过值将$this 分配给一个变量,但它显然最终是通过引用分配的,为什么?我该怎么做?
以下脚本是一组Test 和TestQuery 两个类。 Test 假定$num 属性中的一个值,然后脚本调用Test->exist(),创建两个变量:$original“按值”和$obj 按引用,此时两者相同。最后脚本调用TestQuery->doit( $obj );假设TestQuery会修改$obj的$code,如果$num的值为2,但结果无效,因为exist()方法中$original和$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;
?>
【问题讨论】:
标签: php class oop object pass-by-reference