Arrays 如何按列名搜索实体中的值?

Arrays 如何按列名搜索实体中的值?,arrays,symfony,object,variables,entity,Arrays,Symfony,Object,Variables,Entity,我正在尝试按列名查找表行中的值: $entity = $this->getDoctrine()->getRepository($EntityName)->findOneBy(['uuid' => $uuid]); $result = $entity->getCat(); 困难在于,我希望能够用变量替换“Cat” 不幸的是,这是不可能的: $myvariable = "Cat"; $result = $entity->'get'.$myvariable.();

我正在尝试按列名查找表行中的值:

$entity = $this->getDoctrine()->getRepository($EntityName)->findOneBy(['uuid' => $uuid]);
$result = $entity->getCat();
困难在于,我希望能够用变量替换“Cat”

不幸的是,这是不可能的:

$myvariable = "Cat";
$result = $entity->'get'.$myvariable.();
因此,我采取了另一种方法:

$entity = $this->getDoctrine()->getRepository($EntityName)->findBy(array('uuid' => $uuid));
$result = array_search($myvariable, $entity);
 foreach ($entity as $key => $value) {
     if($myvariable == $key){
            $result = $value;
     }
  }
但这里我得到一个空输出

另一种方法:

$entity = $this->getDoctrine()->getRepository($EntityName)->findBy(array('uuid' => $uuid));
$result = array_search($myvariable, $entity);
 foreach ($entity as $key => $value) {
     if($myvariable == $key){
            $result = $value;
     }
  }
此处的错误消息是:

在呈现模板期间引发了异常 (“可捕获的致命错误:类App\Entity\Documents的对象可能 不能转换为字符串“)


我只是很难找到正确的方法来实现我的目标。

你可以试着通过反思来实现这一点。这里有一个简单的例子

<?php

class ClassName
{

    private $property1;
    private $property2;

    public function __construct($property1, $property2)
    {
        $this->property1 = $property1;
        $this->property2 = $property2;
    }

    public function getProperty1()
    {
        return $this->property1;
    }

    public function getProperty2()
    {
        return $this->property2;
    }
}


$class = new ClassName('test1', 'test2');

$field = 'property2';

$reflectionClass = new \ReflectionClass($class);

if ($reflectionClass->hasProperty($field)) {
    $property = $reflectionClass->getProperty($field);
    $property->setAccessible(true);
    echo $property->getValue($class);
}

// or

echo $class->{sprintf('get%s', ucfirst($field))}();
尝试使用:


哇,这太复杂了。没有简单的解决方案?用一个更简单的例子更新了答案。反射是一件有趣的事情,你应该读一读$getObj=(字符串)$myvariable$结果=$entity->$getObj()