Symfony调用通过名称获取变量

The*_*Tom 5 getter symfony

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

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

$array=Array('id','email','name');
Run Code Online (Sandbox Code Playgroud)

通常,我会调用-> getId()或-> getEmail()。

在这种情况下,我没有机会处理这样的事情。是否有可能将变量作为get Command的一部分获取,例如...

foreach ($array as $item){
   $value[]=$repository->get$item();
}
Run Code Online (Sandbox Code Playgroud)

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

alt*_*aus 8

Symfony 提供了一个特别的PropertyAccessor你可以使用:

use Symfony\Component\PropertyAccess\PropertyAccess;

$accessor = PropertyAccess::createPropertyAccessor();

class Person
{
    private $firstName = 'Wouter';

    public function getFirstName()
    {
        return $this->firstName;
    }
}

$person = new Person();

var_dump($accessor->getValue($person, 'first_name')); // 'Wouter'
Run Code Online (Sandbox Code Playgroud)

http://symfony.com/doc/current/components/property_access/introduction.html#using-getters


Gui*_*che 4

你可以这样做:

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

作为$yourObject您想要从中获取 id 的对象。

编辑:不要忘记使用添加:

use ReflectionMethod;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。