2010-06-20 52 views
4

在PHP中使用__set訪問函數我可以設置標量的值,但不能設置數組的元素。即:PHP訪問函數和數組

$p->scalavar = "Hello"; // This works fine 
$p->myarray['title'] = "Hello"; //This does not work 

我訪問如下:

function __set($mbr_name, $mbr_value) { 
    $this->$mbr_name = $mbr_value; 
} 

謝謝!

回答

9
$p->myarray['title'] = "Hello"; 

這不叫__set魔法;你不是完全設置屬性,你正在改變它的一部分。在這種情況下,如果存在這種魔術方法,PHP將調用__get方法來檢索存儲在屬性$p->myarray中的數組。請注意,要更改返回的值以便對屬性產生任何影響,您必須通過參考返回:

function &__get($mbr_name) { 
    return $this->$mbr_name; 
}