Concatenate php variable in object method name

Viewed 1147
  • I've method getFoo, getBar
  • I've array [Foo, bar]
  • I want in the loop to get method dynamically

example:

class Item {
    getFoo();...
    getBar();...
}

$methods = ['Foo','Bar'];

...
foreach($methods as $method){
    $methodName = 'get'.$method.'()';
    $item->{$methodName}; //Notice: Undefined property: Item::$getFoo()
 }

//"Item->$getFoo()"  instead of "Item->getFoo()" probleme is $
1 Answers
class Item {
    getFoo();...
    getBar();...
}

$methods = ['Foo','Bar'];

...
foreach($methods as $method){
    $methodName = 'get'.$method;//this is the good way
    $item->$methodName();//the bracket make PHP consider this as function call instead of a simple property
 }
Related