我有一個對象$var
它具有3個屬性one
two
three
。我試圖將這些屬性存儲在數組$info
中。PHP中的可變對象屬性
很長的路要走:
$info['one'] = $var->one;
$info['two'] = $var->two;
$info['three'] = $var->three;
在未來的某個時刻的3個屬性會變得更多,所以我嘗試使用foreach
循環存儲在我的數組的屬性。
$attributes = array('one', 'two', 'three');
foreach ($attributes as $attribute) {
$info[$attribute] = $var->$attribute; // My problem is here
}
我遇到的問題是你不能這樣做:$var->$attribute
。
如何爲我的對象的屬性使用變量?
爲什麼你不應該是能夠做到這一點?你有任何錯誤?該代碼適用於我。 – Rizier123
試試'$ var - > {$ attribute}'或者我只是做'$ info = get_object_vars($ var)'。 – AbraCadaver
@ Rizier123你說我**可以**嗎? – henrywright