首页 > 解决方案 > 在对象方法名称中连接 php 变量

问题描述

例子:

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 $

标签: phpobjectmethodsconcatenation

解决方案


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
 }

推荐阅读