Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[PropertyAccess] Document nullsafe operator usage #17288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions components/property_access.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::

// ...
Expand Down Expand Up @@ -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``.
Expand Down