PHP中的对象是按值或引用传递的吗? [英] Are objects in PHP passed by value or reference?

查看:96
本文介绍了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.

这篇关于PHP中的对象是按值或引用传递的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆