Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[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
[PropertyAccess] Document nullsafe operator usage
  • Loading branch information
fsoedjede committed Sep 22, 2022
commit 6a5d2eec0e9d3fa46fa56f4b4f2faf183cf7bd65
33 changes: 33 additions & 0 deletions 33 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
Morty Proxy This is a proxified and sanitized view of the page, visit original site.