我有一个字段数据库记录行,如下所示:
| id | command |
------------------
| 1 | getName() |
我还有一个用户的PHP实体,并且具有getName()
功能。
假设读取数据库记录并将其解析为$ record并且我有$ user,如何将$ record与$ user命令连接?
我试过了$user-> . $record['command']
,但显然不起作用。我想避免硬编码,因为我需要它是动态的。如果可能的话。
代码示例:
$record = DB::queryFirstRow("SELECT * from command_records WHERE id='1'");
$user = new User("Kenny");
// Here is where I'm trying to perform the $user->getName()
// by reading $record['command']. $record['command'] is getName()
$user-> . $record['command'];
当然失败了。我之前在谷歌上搜索eval,但也无法解决这个问题。
答案 0 :(得分:2)
您正在寻找的是PHP's variable variables
您可以尝试以下内容:
class User
{
public function getName()
{
return "SomeName";
}
}
// assuming this is how your result looks like
$result = [
'command' => 'getName()',
// more data
];
$command = $result['command']; // is "getName()"
$command = str_replace('()','',$command); // is "getName"
// you need to remove the '()'. just get the name of the method
$user = new User();
echo $user->{$command}();
// output: SomeName
请在此处查看:https://3v4l.org/OVYAa