1
我不確定我的改變特性的方法將其推到一個數組後其原有的指針,值的對象的。
在我的父類中,有一個對象數組,並且將項目推入它的函數返回原始實例。更改屬性值通過保持原始實例
class Parent {
public $items;
function __construct() { $items = array(); }
function addItem() {
$item = new stdClass();
$item->foo = 'foo';
$items[] = $item;
return $item;
}
}
中的子類,我得到的原始實例,我可以很容易地改變其foo
屬性值:
class Child extends Parent {
function newItem() {
$item_instance = $this->addItem();
$item_instance->foo = 'bar';
}
}
當我實例兒童類,它的行爲如預期,改變了數組項父類的屬性值。
$my_child = new Child();
$my_child->newItem();
print $my_child->items[0]->foo; // prints 'bar'
我的問題是:我應該避免使用原來的對象指針的對象推入陣後,或者是這種做法是否正確?
謝謝。你知道任何可能說明上述情況的文檔嗎? – mavrosxristoforos
@mavrosxristoforos,這是PHP自5.0以來的基本特性,您可以從這裏開始:http://www.php.net/manual/en/oop5.intro.php –
謝謝。事實上,我已經看到了oop5文檔,而且這是按預期工作的,所以我現在就放心了。 – mavrosxristoforos