Symfony调用来自变量的Name

问题描述 投票:3回答:3

我想用数据库中存储的fieldname调用getter。

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

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

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

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

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

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

symfony getter
3个回答
3
投票

你可以这样做:

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

$yourObject是你想从中获取id的对象。

编辑:不要忘记添加的用途:

use ReflectionMethod;

希望这可以帮助。


4
投票

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'

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


1
投票
<?php
// You can get Getter method like this
use Doctrine\Common\Inflector\Inflector;

$array = ['id', 'email', 'name'];
$value = [];

foreach ($array as $item){
    $method = Inflector::classify('get_'.$item);
    // Call it
    if (method_exists($repository, $method))
        $value[] = $repository->$method();
}
© www.soinside.com 2019 - 2024. All rights reserved.