PHP:美丽的动态语言。设计模式
我有以下模式。或者更好的想法! 有从 BaseUnit
继承的“unit”类和从 BaseUser
继承的“users”类。后代单位和后代用户在结构上非常相似。
我想为使用单元的用户应用“工具栏”功能
它看起来像
class KickerUser extends BaseUser{
public $toolbar = array('view()', 'kick("right_leg", "twice")')
}
class BaseUnit{
public function view();
public function kick($a, $b);
public function bite($c);
protected function applyToolbar($user){
///////////////HERE COMES THE TRICK////////
foreach($user->toolbar as $t){
$this->$t;
}
// should I use eval() for this
// to become something like: $this->bite('hard');
// i'm interested in making the readable code
// and passing constant parameters
/////////////HOW TO WRTITE THIS CORRECTLY ?
}
}
这是一种很好的做事方式吗?
I have the following pattern. Or better the IDEA!
There are "unit" classes inherited from BaseUnit
and "users" classes inherited from BaseUser
. Descendant units and descendant users are pretty similar in structure.
I want to apply a "toolbar" feature for users working with units
It can look like
class KickerUser extends BaseUser{
public $toolbar = array('view()', 'kick("right_leg", "twice")')
}
class BaseUnit{
public function view();
public function kick($a, $b);
public function bite($c);
protected function applyToolbar($user){
///////////////HERE COMES THE TRICK////////
foreach($user->toolbar as $t){
$this->$t;
}
// should I use eval() for this
// to become something like: $this->bite('hard');
// i'm interested in making the readable code
// and passing constant parameters
/////////////HOW TO WRTITE THIS CORRECTLY ?
}
}
Is this a good way of doing things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我本想给你指出卡萨布兰卡给你指出的同一个方向,但他抢先了我:)。
不过,这里有一个您可能会发现有用的小示例:
祝您好运,
阿林
I was going to point you in the same direction that casablanca pointed you in, but he beat me to it :) .
Nevertheless, here's a little example you may find useful:
Good luck,
Alin
除非没有更好的解决方案,否则不要使用
eval
。就您而言,事实证明有一个更好的解决方案 -call_user_func
和call_user_func_array
。这两个函数之间的区别在于是直接传递参数还是作为数组传递参数。例如,如果您想调用
$this->kick('right_leg', 'twice')
,您可以将其写为:或:
您可以轻松地使其动态化:
Don't use
eval
unless there isn't a better solution. In your case, it turns out there is a better solution --call_user_func
andcall_user_func_array
. The difference between the two functions is whether you pass the parameters directly or as an array.For example, if you want to call
$this->kick('right_leg', 'twice')
, you could write it as:or:
You can easily make this dynamic: