首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >连接对象方法名中的php变量

连接对象方法名中的php变量
EN

Stack Overflow用户
提问于 2018-09-14 07:56:09
回答 1查看 868关注 0票数 1

我有

  • getFoo,getBar

  • ,I‘s array Foo,bar

  • 我想要在循环中动态获取方法

示例:

代码语言:javascript
复制
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 $
EN

回答 1

Stack Overflow用户

发布于 2018-09-14 08:13:22

代码语言:javascript
复制
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
 }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52323230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档