Skip to content

Commit dabd9ce

Browse files
committed
minor #17288 [PropertyAccess] Document nullsafe operator usage (fsoedjede)
This PR was merged into the 6.2 branch. Discussion ---------- [PropertyAccess] Document nullsafe operator usage <!-- If your pull request fixes a BUG, use the oldest maintained branch that contains the bug (see https://symfony.com/releases for the list of maintained branches). If your pull request documents a NEW FEATURE, use the same Symfony branch where the feature was introduced (and `6.x` for features of unreleased versions). --> Doc PR for symfony/symfony#47511 Commits ------- 6a5d2ee [PropertyAccess] Document nullsafe operator usage
2 parents dbf5802 + 6a5d2ee commit dabd9ce

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

components/property_access.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ method::
6363
// Symfony\Component\PropertyAccess\Exception\NoSuchIndexException
6464
$value = $propertyAccessor->getValue($person, '[age]');
6565

66+
// You can avoid the exception by adding the nullsafe operator
67+
$value = $propertyAccessor->getValue($person, '[age?]');
68+
6669
You can also use multi dimensional arrays::
6770

6871
// ...
@@ -101,6 +104,36 @@ To read from properties, use the "dot" notation::
101104

102105
var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar'
103106

107+
.. tip::
108+
109+
You can give an object graph with nullable object.
110+
111+
Given an object graph ``comment.person.profile``, where ``person`` is optional (can be null),
112+
you can call the property accessor with ``comment.person?.profile`` (using the nullsafe
113+
operator) to avoid exception.
114+
115+
For example::
116+
117+
class Person
118+
{
119+
}
120+
class Comment
121+
{
122+
public ?Person $person = null;
123+
public string $message;
124+
}
125+
126+
$comment = new Comment();
127+
$comment->message = 'test';
128+
129+
// This code throws an exception of type
130+
// Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException
131+
var_dump($propertyAccessor->getValue($comment, 'person.firstname'));
132+
133+
// The code now returns null, instead of throwing an exception of type
134+
// Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException,
135+
var_dump($propertyAccessor->getValue($comment, 'person?.firstname')); // null
136+
104137
.. caution::
105138

106139
Accessing public properties is the last option used by ``PropertyAccessor``.

0 commit comments

Comments
 (0)