使用php函数返回元素(Returning elements with php functions)

我有一个这样的课:

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

我期望以下代码修改我的数组元素:

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

相反,在运行我的代码时, $elements['foo1']的active属性仍然是假的,因为它在调用getElementByName之前是

我认为该函数对元素进行了“复制”,我怎样才能得到数组的真实元素,这样当我修改它,然后在数组中访问它时,它的值会发生变化?

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?

最满意答案

返回对它的引用 (注意 ):

function &getElementByName($name) { ... }

Return a reference to it (notice the &):

function &getElementByName($name) { ... }

更多推荐