Symfony call get by Name from variable

 ̄綄美尐妖づ 提交于 2019-12-05 08:40:33

You can do it like this :

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

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

EDIT : Don't forget the use to add :

use ReflectionMethod;

Hope this helps.

Symfony offers a special PropertyAccessor you could use:

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

<?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();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!