3

I have a class like this:

class Foo {
    $elements = array();

    function getElementByName($name) {
        foreach($this->elements as $elm) {
            if ($elm->name == $name) {
                return $elm;
            }
        }
    }
}

I expected the following code to modify the element of my array:

$myFoo = new Foo();
$myFoo->getElementByName('foo1')->active = true;

Instead, when running my code, the active property of $elements['foo1'] is still false as it was before calling getElementByName

I think that the function makes a "copy" of the element, how can I get the real element of the array, so that when I modify it, and then access it in the array, its values have changed?

3
  • 2
    I cannot reproduce the behavior: codepad.org/7RFtib1d Commented Oct 13, 2013 at 10:56
  • You assume right. But note that PHP since version 5 should pass objects by reference anyway. Are you still running PHP 4? Commented Oct 13, 2013 at 10:58
  • @knittl PHP 4.4.9 will throw unexpected T_OBJECT_OPERATOR. Commented Oct 13, 2013 at 11:01

2 Answers 2

3

Return a reference to it (notice the &):

function &getElementByName($name) { ... }
Sign up to request clarification or add additional context in comments.

Comments

1

Return a reference to the element:

function &getElementByName($name) { // & returns by reference
    foreach($this->elements as $elm) {
        if ($elm->name == $name) {
            return $elm;
        }
    }
}

Starting with PHP 5 objects are passed by reference by default.

1 Comment

Actually, object references are passed by value.

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.