簡體   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