繁体   English   中英

PHP函数,按值还是按引用返回?

[英]PHP function, return by value or by reference?

当我在PHP中使用return语句时,结果将按值还是按引用返回?

谢谢! ANDREE。

在PHP中,默认情况下,所有内容均按值返回(我敢肯定会有例外,但我无法想到任何atm)。 默认情况下通过引用传递的对象(PHP> 5.0)除外。

显然,它是通过引用返回的。 这个简单的代码证明了这一点。

<?php

class InsideObject
{
    public $variable;
}

class OutsideObject
{
    private $insideObject;

    public function __construct()
    {
        $this->insideObject = new InsideObject();
        $this->insideObject->variable = '1';
    }

    public function echoVar()
    {
        echo $this->insideObject->variable;
    }

    public function getInsideObject()
    {
        return $this->insideObject;
    }
}

$object = new OutsideObject();
$object->echoVar(); // should be 1

$insideObject = $object->getInsideObject();
$insideObject->variable = '2';

$object->echoVar(); // should be 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM