2014-07-25 107 views
2

我想將一個簡單的字符串,如「response-> dict-> words」變成一個我實際可以使用的變量名。我現在舉個例子。讓我們假設值爲$response->dict->words is 67將字符串轉換爲對象變量名稱?

例子:

$var = "response->dict->words" 

echo $$var; /* PRINT THE VALUE 67 FROM $response->dict->words*/ 

正如你可能會注意到,我把一個額外的美元符號$ VAR之前,因爲這應該工作,但事實並非如此。

任何人都可以幫助我嗎?

+3

這裏你應該用'的eval()的',而不是可變的變量或類似的東西,但你更好地重構你的邏輯。應該不需要進行字符串 - >對象調用。 –

回答

-4

有一個更好的辦法,你爲什麼不喜歡緩存

 $var = $response->dict->words; 
變量
+2

,因爲他沒有變量,但字符串 –

5
class ClassOne { 
    public function test() { 
     return 'test'; 
    } 
} 

class ClassTwo { 
    public function test2() { 
     return 'test2'; 
    } 
} 

$one = new ClassOne(); 
$two = new ClassTwo(); 

$objects = array('one', 'two'); 
$methods = array('test', 'test2'); 

for ($i = 0; $i < count($objects); $i++) { 
    echo ${$objects[$i]}->$methods[$i](); 
} 

可以存儲類名或方法名作爲字符串並在以後使用它們,甚至存儲變量名,如這裏是${$objects}(變量變量),但是你不能存儲整個邏輯。

評價整個邏輯,你必須使用eval(),這是最有可能壞主意

$var = "response->dict->words" 
eval("?> <?php echo $".$var.";"); 

您可以分割你的字符串,並作出以下電話:

class Response { 
    public $dict; 

    public function __construct() { 
     $this->dict = new stdClass(); 
     $this->dict->words = 'words test'; 
    } 
} 

$response = new Response(); 

$var = 'response->dict->words'; 

$elements = explode('->', $var); 

echo ${$elements[0]}->$elements[1]->$elements[2]; 

結果爲words test或者,如果您不知道嵌套對象調用的級別,則可以在foreach循環中執行調用。當退出循環,最後調用將後可用:

class Response { 
    public $dict; 

    public function __construct() { 
     $this->dict = new stdClass(); 
     $this->dict->words = new stdClass(); 
     $this->dict->words->final = 'test chained string'; 
    } 
} 

$response = new Response(); 

$var = 'response->dict->words->final'; 

$elements = explode('->', $var); 

foreach ($elements as $key => $element) { 
    if ($key == 0) { 
     $call = ${$element}; 
     continue; 
    } 
    $call = $call->$element; 
} 

echo $call; 

結果爲:test chained string

+0

我仍然沒有得到使用$ call = $ call - > $ element –