@@ -104,36 +104,6 @@ To read from properties, use the "dot" notation::
104
104
105
105
var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar'
106
106
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
-
137
107
.. caution ::
138
108
139
109
Accessing public properties is the last option used by ``PropertyAccessor ``.
@@ -223,6 +193,39 @@ method::
223
193
// instead of throwing an exception the following code returns null
224
194
$value = $propertyAccessor->getValue($person, 'birthday');
225
195
196
+ Accessing Nullable Property Paths
197
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198
+
199
+ Consider the following PHP code::
200
+
201
+ class Person
202
+ {
203
+ }
204
+
205
+ class Comment
206
+ {
207
+ public ?Person $person = null;
208
+ public string $message;
209
+ }
210
+
211
+ $comment = new Comment();
212
+ $comment->message = 'test';
213
+
214
+ Given that ``$person `` is nullable, an object graph like ``comment.person.profile ``
215
+ will trigger an exception when the ``$person `` property is ``null ``. The solution
216
+ is to mark all nullable properties with the nullsafe operator (``? ``)::
217
+
218
+ // This code throws an exception of type
219
+ // Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException
220
+ var_dump($propertyAccessor->getValue($comment, 'person.firstname'));
221
+
222
+ // If a property marked with the nullsafe operator is null, the expression is
223
+ // no longer evaluated and null is returned immediately without throwing an exception
224
+ var_dump($propertyAccessor->getValue($comment, 'person?.firstname')); // null
225
+
226
+ .. versionadded :: 6.2
227
+
228
+ The ``? `` nullsafe operator was introduced in Symfony 6.2.
226
229
227
230
.. _components-property-access-magic-get :
228
231
0 commit comments