是否有相当于创建新类实例的 call_user_func() ?
如何创建一个类,并将给定的参数数组发送给构造函数?大致如下:
class a {
var $args = false;
function a() {$this->args = func_get_args();}
}
$a = call_user_func_array('new a',array(1,2,3));
print_r($a->args);
理想情况下,这需要在 PHP4 和 PHP5 中都可以工作,而不需要修改类。有什么想法吗?
How can I create a class with a given array of arguments to be sent to the constructor? Something along the lines of:
class a {
var $args = false;
function a() {$this->args = func_get_args();}
}
$a = call_user_func_array('new a',array(1,2,3));
print_r($a->args);
Ideally this needs to work, without modification to the class, in both PHP4 and PHP5. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ReflectionClass:newInstance() (或 newInstanceArgs())让您做到这一点。
例如
编辑:没有ReflectionClass并且可能兼容php4(抱歉,现在手头没有php4)
速度比较:
既然已经提到了反射速度,这里有一个小(综合)测试
,它打印在我的(不太快)笔记本上
,这不是很糟糕吗?
ReflectionClass:newInstance() (or newInstanceArgs()) let's you do that.
e.g.
edit: without ReflectionClass and probably php4 compatible (sorry, no php4 at hand right now)
speed comparison:
Since the speed of reflection has been mentioned here's a little (synthetic) test
which prints on my (not so fast) notebook
Isn't that bad, is it?
查看工厂方法模式并查看此示例
来自维基百科:
如果您不想为此使用专用工厂,您仍然可以 将 Volker 的代码包装到一个函数中,例如
Have a look at the Factory Method pattern and check out this example
From Wikipedia:
If you don't want to use a dedicated Factory for this, you could still wrap Volker's code into a function, e.g.