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?
Don’t use
evalunless there isn’t a better solution. In your case, it turns out there is a better solution —call_user_funcandcall_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: