Sending Symfony Call by Name from Variable
I would like to call a getter with a stored field name from the database.
For example, there are some field names like ['id', 'email', 'name'].
$array=Array('id','email','name');
I usually call → getId () or → getEmail () ....
In this case, I have no chance of handling such things. Is it possible to get a variable as part of a get command like ...
foreach ($array as $item){
$value[]=$repository->get$item();
}
Can I use the magic method in some way? this is a little confusing ....
source to share
You can do it like this:
// For example, to get getId()
$reflectionMethod = new ReflectionMethod('AppBundle\Entity\YourEntity','get'.$soft[0]);
$i[] = $reflectionMethod->invoke($yourObject);
C $yourObject
, which is the object from which you want to get the id.
EDIT: Don't forget to add:
use ReflectionMethod;
Hope it helps.
source to share
Symfony offers a special PropertyAccessor
one that 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
source to share
<?php
// You can get Getter method like this
use Doctrine\Common\Inflector\Inflector;
$array = ['id', 'email', 'name'];
$value = [];
foreach ($array as $item){
$camelCase = Inflector::classify($item);
$method = 'get' . $camelCase;
// Call it
if (method_exists($repository, $method))
$value[] = $repository->$method();
}
source to share