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

时间:2016-02-01 12:13:02

标签: php string class instance dynamically-generated

假设我有一个名为“翻译”的课程。 我有一个名为'chinese_translations'的类的实例

$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

3 个答案:

答案 0 :(得分:2)

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

试试这个:

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

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

详细了解variable variables

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:0)

最后,括号版本做了这个伎俩,但是有一个范围问题,所以两个答案都可能正确。这一个:

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

目前正在为我工​​作。