php - 在对象方法名称中连接 php 变量
问题描述
- 我有方法 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 $
解决方案
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
}
推荐阅读
- c++ - 指针数组无法从指针函数中获取数据的问题
- javascript - 如何根据菜单选项更改页面内容?
- c# - C# Linq 计算具有特定值的 XML 段
- search - 自定义域搜索栏 WHMCS 集成
- sql - 如何在数据集中获得每小时?
- c# - 如何更改 ReadAsync 返回的数据格式以使用 dataTables?
- fb-hydra - 如何从以前的作业中加载 Hydra 参数(无需使用 argparse 和 compose API)?
- load-testing - 不能从 Locust 生成超过 ~8000 RPM
- json - JSLT:不是通过索引而是通过表达式访问或查询数组元素
- css - 使用 esc 键离开焦点后的按钮轮廓