Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning elements with php functions

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?

like image 346
Twinone Avatar asked May 25 '26 15:05

Twinone


2 Answers

Return a reference to it (notice the &):

function &getElementByName($name) { ... }
like image 57
OneOfOne Avatar answered May 27 '26 04:05

OneOfOne


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.

like image 37
knittl Avatar answered May 27 '26 05:05

knittl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!