From 6a5d2eec0e9d3fa46fa56f4b4f2faf183cf7bd65 Mon Sep 17 00:00:00 2001 From: Felix Soedjede Date: Fri, 23 Sep 2022 00:41:40 +0200 Subject: [PATCH] [PropertyAccess] Document nullsafe operator usage --- components/property_access.rst | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/components/property_access.rst b/components/property_access.rst index 956e78531d5..9a2890b3e88 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -63,6 +63,9 @@ method:: // Symfony\Component\PropertyAccess\Exception\NoSuchIndexException $value = $propertyAccessor->getValue($person, '[age]'); + // You can avoid the exception by adding the nullsafe operator + $value = $propertyAccessor->getValue($person, '[age?]'); + You can also use multi dimensional arrays:: // ... @@ -101,6 +104,36 @@ To read from properties, use the "dot" notation:: var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar' +.. tip:: + + You can give an object graph with nullable object. + + Given an object graph ``comment.person.profile``, where ``person`` is optional (can be null), + you can call the property accessor with ``comment.person?.profile`` (using the nullsafe + operator) to avoid exception. + + For example:: + + class Person + { + } + class Comment + { + public ?Person $person = null; + public string $message; + } + + $comment = new Comment(); + $comment->message = 'test'; + + // This code throws an exception of type + // Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException + var_dump($propertyAccessor->getValue($comment, 'person.firstname')); + + // The code now returns null, instead of throwing an exception of type + // Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException, + var_dump($propertyAccessor->getValue($comment, 'person?.firstname')); // null + .. caution:: Accessing public properties is the last option used by ``PropertyAccessor``.