从PHP中的变量实例化一个类? [英] instantiate a class from a variable in PHP?

查看:334
本文介绍了从PHP中的变量实例化一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题听起来比较模糊,所以我将使用一个例子更清楚:

I know this question sounds rather vague so I will make it more clear with an example:

$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');

这是我想做的。你会怎么做?我可以使用eval()像这样:

This is what I want to do. How would you do it? I could off course use eval() like this:

$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');

但我宁愿远离eval()。有没有办法这样做没有eval()?

But I'd rather stay away from eval(). Is there any way to do this without eval()?

推荐答案

将类名先放入变量:

$classname=$var.'Class';

$bar=new $classname("xyz");

这通常是你看到的以工厂模式包装的东西。

This is often the sort of thing you'll see wrapped up in a Factory pattern.

请参阅命名空间和动态语言功能了解详情。

这篇关于从PHP中的变量实例化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆