Symfony PropertyAccessor setValue在对象上提供NoSuchPropertyException

时间:2019-05-08 16:39:17

标签: php symfony properties

在我的代码中,我想从约束违例中提取消息和字段 成阵列。 PropertyAccess为此setValue。它适用于数组键,但不适用于对象属性。

在对象属性上使用setValue会导致

fatal error: Uncaught Symfony\Component\PropertyAccess\Exception
\NoSuchPropertyException: Cannot write property "first_name" to an array. 
Maybe you should write the property path as "[first_name]" instead?

据我了解,PropertyAccess统一了对数组和对象的访问。为什么setValue无法处理对象属性?

这是代码段:

$user = new User('', 'Novak', 'pnovak@examplecom');

$validator =   Validation::createValidatorBuilder()->addXmlMapping('validation.xml')->getValidator();
$violations = $validator->validate($user);

$accessor = PropertyAccess::createPropertyAccessor();

$messages = [];

if (0 === count($violations)) {

    echo 'validation passed';
} else {

    foreach ($violations as $violation) {


        // $messages[$violation->getPropertyPath()] = $violation->getMessage();

        $accessor->setValue($messages,
            $violation->getPropertyPath(),
            $violation->getMessage());
    }

    dump($messages);
}

0 个答案:

没有答案