如何用未知参数初始化对象?
我正在尝试创建一个类,其中包含使用 PHP 的 __call() 魔术方法调用的方法。然后,这个神奇的方法将初始化另一个对象,如下所示:
public function __call($function, $arguments) {
/* Only allow function beginning with 'add' */
if ( ! preg_match('/^add/', $function) ) {
trigger_error('Call to undefined method ' . __CLASS__ . '::' . $function, E_USER_ERROR);
}
$class = 'NamodgField_' . substr($function, 3); /* Ex: $function = addTextField() => $class = NamodgField_TextField */
/* This doesn't work! Because $class is not an object yet */
call_user_func_array( array(new $class, '__construct'), $arguments);
}
该代码的最后一行完全磨损了!我只是想弄清楚我想做什么。
我希望能够在初始化一个新对象时一个接一个地传递 $arguments
,以便每个子类都可以定义其必要的参数。
我想出了一个使用 eval()
的解决方案,但我真的不喜欢它。
有什么想法吗?
I'm trying to make a class which has methods called using PHP's __call()
magic method. This magic method will then be initializing another object like this :
public function __call($function, $arguments) {
/* Only allow function beginning with 'add' */
if ( ! preg_match('/^add/', $function) ) {
trigger_error('Call to undefined method ' . __CLASS__ . '::' . $function, E_USER_ERROR);
}
$class = 'NamodgField_' . substr($function, 3); /* Ex: $function = addTextField() => $class = NamodgField_TextField */
/* This doesn't work! Because $class is not an object yet */
call_user_func_array( array(new $class, '__construct'), $arguments);
}
The last line of that code is totally worng! I'm just trying to make clear what I want to do.
I want to be able to pass the $arguments
when initializing a new object, one after the other, So that each child class could define it's necessary arguments.
I figured a solution using eval()
, but I really don't like it.
Any Ideas ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)