2017-04-24 142 views
1

我嘗試訪問使用字符串變量具有數組形式的對象屬性,但當字符串包含索引選擇時無法這樣做。看看這個例子..我一直在特林要做的就是用$ access3像串使用字符串訪問對象的數組屬性

$dummy = new stdClass(); 
$dummy->testNormal = 'itemNormal'; 
$dummy->testArray = array('item1', 'item2'); 

$access1 = 'testNormal'; 
$access2 = 'testArray'; 
$access3 = 'testArray[0]'; 

echo 'try access1: ' . $dummy->{$access1} . '<br />'; 
echo 'try access2: ' . $dummy->{$access2}[0] . '<br />'; 
echo 'try access3: ' . $dummy->{$access3} . '<br />'; 
echo 'try direct: ' . $dummy->testArray[0] . '<br />'; 

上面的代碼將返回

try access1: itemNormal 
try access2: item1 
--- ERROR MESSAGE -- 
try access3:  <-- does not contain anything because of error, my expectation is it will be "item1" 
try direct: item1 

這是不可能用PHP?

+0

這可能與eval我認爲,但你應該忘記這種方法。我很確定有更好的解決方案,比如你想要什麼 – Peter

+0

恐怕不能在一次通話中完成。一種解決方案可以是在[,並且調用$ dummy - > {<>} 之前將字符串拆分,但是您不能執行testArray [0] [1] [2] ... [n]除非你寫一個函數來分割字符串並返回所需的對象元素 –

回答

0
$access_handler = explode('[', $access3); 
// get array name 
$array_name = $access_handler[0]; 
// get array index 
$array_index = substr($access_handler[1], 0, -1); 
// call the property 
echo $dummy->$array_name[$array_index]; 

您可能會爲此創建函數。否則,你將不得不使用eval來評估你的字符串,但這不推薦。也有很多方法來從數組名稱分離索引,然後運行它,如在這個例子中