【问题标题】:Concatenate php variable in object method name在对象方法名称中连接 php 变量
【发布时间】:2018-09-13 23:56:08
【问题描述】:
  • 我有 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】:
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
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多