php 从动态生成的字符串调用 class 实例

php invoke class instance from dynamically generated string

假设我有一个名为 'translations' 的 class。 我有一个名为 'chinese_translations'

的 class 实例
$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

我总是收到 "Call to a member function getMsg() on a non-object" 消息。 我做错了什么?

*采取的一些行动和取得的成果:

//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

试试这个:

$className = $part1.$part2;
$instance = new $$className;
$instance->getMsg();

$part1.$part2 是一个字符串。因此,$instance_of_translations是变量名,而不是变量本身。

试试这个:

$part1 = 'chinese_';
$part2 = 'translations';
$varName = $part1.$part2;
$instance_of_translations = $$varName;
var_dump($instance_of_translations);

它应该显示类型为 translations 的对象。

详细了解 variable variables

括号版本终于成功了,但是存在范围问题,所以两个答案都可能是正确的。这个:

 $part1 = 'chinese_';
 $part2 = 'translations';
 $instance_of_translations = ${$part1.$part2};
 $instance_of_translations->getMsg();

目前正在为我工​​作。