PHP中的对象是按值或引用传递的吗?
在此代码中:
<?php
class Foo
{
var $value;
function foo($value)
{
$this->setValue($value);
}
function setValue($value)
{
$this->value=$value;
}
}
class Bar
{
var $foos=array();
function Bar()
{
for ($x=1; $x<=10; $x++)
{
$this->foos[$x]=new Foo("Foo # $x");
}
}
function getFoo($index)
{
return $this->foos[$index];
}
function test()
{
$testFoo=$this->getFoo(5);
$testFoo->setValue("My value has now changed");
}
}
?>
运行方法Bar::test()
并更改foo对象数组中foo#5的值时,将影响数组中实际的foo#5,或者$testFoo
变量仅是局部变量变量在函数末尾会不复存在?
When the method Bar::test()
is run and it changes the value of foo # 5 in the array of foo objects, will the actual foo # 5 in the array be affected, or will the $testFoo
variable be only a local variable which would cease to exist at the end of the function?
为什么不运行该函数并找出来?
Why not run the function and find out?
$b = new Bar;
echo $b->getFoo(5)->value;
$b->test();
echo $b->getFoo(5)->value;
对我来说,上面的代码(以及您的代码)产生了以下输出:
For me the above code (along with your code) produced this output:
Foo #5
My value has now changed
这不是由于按引用传递",而是由于按引用分配".在PHP 5中,按引用分配是对象的默认行为.如果您想按值分配,请使用 clone 关键字
This isn't due to "passing by reference", however, it is due to "assignment by reference". In PHP 5 assignment by reference is the default behaviour with objects. If you want to assign by value instead, use the clone keyword.