Php Symfony使用eval执行实体方法
我正在尝试使用基于字符串的方法运行实体方法。但这似乎不起作用,并产生以下错误: 注意:未定义的属性:AppBundle\Entity\User::$setName 内部控制器Php Symfony使用eval执行实体方法,php,eval,Php,Eval,我正在尝试使用基于字符串的方法运行实体方法。但这似乎不起作用,并产生以下错误: 注意:未定义的属性:AppBundle\Entity\User::$setName 内部控制器 $user = $this->getDoctrine()->getRepository("AppBundle:User")->find(1); $value = "Peter"; $method = "setName(".$value.")"; eval($user->$method); /**
$user = $this->getDoctrine()->getRepository("AppBundle:User")->find(1);
$value = "Peter";
$method = "setName(".$value.")";
eval($user->$method);
/**Tried this also but same error **/
$user->{$method}
如何实现这一点?首先,您必须将
$method
变量更改为简单的函数/方法名称,然后可以像最后一行一样对其进行计算
$user = $this->getDoctrine()->getRepository("AppBundle:User")->find(1);
$value = "Peter";
// Just the method name
$method = "setName";
// This is a valid evaluation passing a variable
$user->{$method}($value);
Jack Skeletron的答案更接近您想要做的,但您也可以使用
call\u user\u func\u array
函数:
$user = $this->getDoctrine()->getRepository("AppBundle:User")->find(1);
$method = 'setName';
$value = 'Peter';
call_user_func_array(array($user, $method), array($value));
使用第二种方法时,应该是这样的:
$user->{$method}($value)