林」想知道如果這是可能的:__set和字符串連接
我已經成功地使用__set()魔術方法將值設置爲一個類的屬性:
class View
{
private $data;
public function __set($key, $value)
{
$this->data[$key] = $value;
}
}
所以我能到:
$view = new View();
$view->whatever = 1234;
問題來了,當我想連接一個字符串爲例。看起來__set()沒有被調用(事實上它沒有被調用)。
$view = new View();
$view->a_string = 'hello everybody'; //Value is set correctly
$view->a_string.= '<br>Bye bye!'; //Nothing happens...
echo $view->a_string;
這輸出「大家好」。我無法在第二個任務中執行__set()。 閱讀php.net它說:
__set() is run when writing data to inaccessible properties.
因此,作爲對a_string已經存在,__set沒有被調用。 我的問題最後是...我怎麼能實現這個連接操作?
注: 好吧......墨菲走過來,只要我這貼給我的答案...
答案(我的理解),是PHP是不能夠決定是否a_string可用,因爲我沒有定義__get()方法。
定義__get()允許php找到當前值a_string,然後使用__set()連接該值。
是的,編輯我的帖子後我看到了這個。 – 2010-09-13 21:24:57
我必須在編輯它時正確放棄這一點。 – 2010-09-13 21:29:25
在旁註:返回NULL而不是空字符串似乎更合適。 – Wrikken 2010-09-14 00:26:34