在对象方法名称中连接php变量

问题描述 投票:0回答:1
  • 我的方法是getFoo,getBar
  • 我有阵列[Foo,bar]
  • 我想在循环中动态获取方法

例:

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 $
php object methods concatenation
1个回答
0
投票
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
 }
© www.soinside.com 2019 - 2024. All rights reserved.