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! Andrew.

+2


a source to share


2 answers


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



+7


a source


It appears to be returned by a link. This simple code confirms this.



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

      

0


a source







All Articles