Symfony调用通过名称获取变量 [英] Symfony call get by Name from variable

查看:68
本文介绍了Symfony调用通过名称获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用数据库中存储的字段名来调用getter.

I would like to call a getter with the stored fieldname from the database.

例如,有一些字段名存储,例如['id','email','name'].

For example, there are some fieldnames store like ['id','email','name'].

$array=Array('id','email','name');

通常,我会呼叫-> getId()或-> getEmail()....

Normally, I will call ->getId() or ->getEmail()....

在这种情况下,我没有机会处理这样的事情.像...

In this case, I have no chance to handle things like this. Is there any possibility to get the variable as part of the get Command like...

foreach ($array as $item){
   $value[]=$repository->get$item();
}

我可以以某种方式使用魔术方法吗?这有点令人困惑....

Can I use the magic Method in someway? this is a bit confusing....

推荐答案

您可以这样做:

// For example, to get getId()
$reflectionMethod = new ReflectionMethod('AppBundle\Entity\YourEntity','get'.$soft[0]);
$i[] = $reflectionMethod->invoke($yourObject);

$yourObject是要从其获取ID的对象.

With $yourObject being the object of which you want to get the id from.

不要忘了添加:

use ReflectionMethod;

希望这会有所帮助.

这篇关于Symfony调用通过名称获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆