简体   繁体   中英

PHP function, return by value or by reference?

When I use return statement in PHP, will the result be returned by value or by reference?

Thanks! Andree.

In PHP, everything is returned by value by default (I'm sure there are exceptions to this but I can't think of any atm). Except objects (PHP>5.0) which are passed by reference by default.

Apparently, it is returned by reference. This simple code proofs it.

<?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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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