Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony call get by Name from variable

Tags:

getter

symfony

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

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

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

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....

like image 295
TheTom Avatar asked Jun 30 '15 14:06

TheTom


1 Answers

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

like image 156
althaus Avatar answered Sep 25 '22 01:09

althaus