可以說我有一個名爲'translations'的類。 我叫類的實例「chinese_translations」php從動態生成的字符串中調用類實例
$chinese_translations = new translations;
之後,我想打電話從一個動態構建的字符串,這種情況下,我已經嘗試了幾種方法:
$part1 = 'chinese_';
$part2 = 'translations';
$instance_of_translations = ${$part1.$part2};
$instance_of_translations->getMsg();//Doesn't work
也是這樣的:
$part1 = 'chinese_';
$part2 = 'translations';
$instance_of_translations = $part1.$part2;
$$instance_of_translations->getMsg();//Doesn't work
我總是得到「調用成員函數getMsg()在一個非對象」消息。 我做錯了什麼?
*採取了一些行動和結果得到:
//Lets see if the var is in scope:
echo $chinese_translations->getMsg(get_locale());//It works
$instance_of_translations = ${$part1.$part2};//Let's try to build the name dynamically
echo $chinese_translations->getMsg(get_locale()); //Call to a member function getMsg() on a non-object
echo $$chinese_translations->getMsg(get_locale()); //Object of class internal_message could not be converted to string in
var_dump($instance_of_translations);//It throws the following:
//object(internal_message)#1956 (1) { ["message"]=> array(2) { ["es_ES"]=> string(19) "The expected result" ["it_IT"]=> string(19) "The expected result" } }NULL
你的第一個例子是在我的電腦上工作。你確定'$ chinese_translations'與你調用'getMsg()'的部分在同一個範圍內嗎? –
你是對的,有一個範圍問題! – user997593