symfony – 获取set属性中的参数类型

使用Symfony 2框架,我有来自数据库的实体和注释.

在我的特殊情况下,我与实体合作,但我不知道我正在使用哪一个.

假设我有一个实体对象$entity

$class = get_class($entity);
$reflect = new \ReflectionClass($class)
$properties = $reflect->getProperties();

foreach($properties as $property) {
   $entity->{'set' .ucfirst(strtolower($property))}($some_value);
   ....
}

有没有办法知道每个属性,它期望什么类型的参数?使用注释?

最佳答案 理论上你可以这样做,但我不知道它会如何影响性能.

您可以使用Doctrine AnnotationReader.

以下是您可以执行的操作的代码示例.

use Doctrine\Common\Annotations\AnnotationReader;

$class = get_class($entity);
$reflect = new \ReflectionClass($class)
$properties = $reflect->getProperties();
$annotationReader = new AnnotationReader();

foreach($properties as $property) {
    $reflectionProperty = new ReflectionProperty($class, $property);
    $propertyAnnotations = $annotationReader->getPropertyAnnotations($reflectionProperty);
    var_dump($propertAnnotations);
    ....
}

除此之外,您可能需要查看Symfony ProppertyAccesor以获取和/或设置特定对象值.
http://symfony.com/doc/current/components/property_access/introduction.html

点赞