2

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

Thanks! Andree.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What did you mean by "it" in this case? Did the code that prompted your question return an object or?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.