PHP 中的对象是按值分配还是按引用分配? [英] Are objects in PHP assigned by value or reference?
问题描述
在这段代码中:
<?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.
这篇关于PHP 中的对象是按值分配还是按引用分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!