Req #75017 [Opn->Dup]: Nullable Method Calling
| From: | cmb@php.net | Date: | Wed, 02 Aug 2017 17:21:53 +0000 |
| Subject: | Req #75017 [Opn->Dup]: Nullable Method Calling | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-210460@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=75017&edit=1
ID: 75017
Updated by: cmb@php.net
Reported by: php at haravikk dot me
Summary: Nullable Method Calling
-Status: Open
+Status: Duplicate
Type: Feature/Change Request
Package: *General Issues
PHP Version: Next Major Version
-Assigned To:
+Assigned To: cmb
Block user comment: N
Private report: N
New Comment:
This feature request is already subject of an existing RFC[1], so
I'm closing this ticket as duplicate. Feel free to push the
dormant RFC.
[1] <https://wiki.php.net/rfc/nullsafe_calls>
Previous Comments:
------------------------------------------------------------------------
[2017-08-01 13:15:33] php at haravikk dot me
Description:
------------
It was great to see the addition of the nil-coalescing operator in PHP 7, but one case that I
encounter a lot but still appears to have no solution is calling a method on a variable that may be
null.
What I'd like to propose is a new nullable method calling operator, which would enable us to
call a method on a variable that may be null; if the variable is null the method call is ignored and
null is returned, otherwise the method is called and its result returned. My proposed operator for
this would be
?->, i.e- a normal method operator, but with a question mark after the
variable indicating that the developer is aware it could be null. Put of another way, if
-> is "call method", then ?-> "call method if not
null".
We could then use this like so:
$array = $object?->getFoo()?->getArray() ?? [];
Here we use the operator to try to drill down into $object, seeking out an array. If
either $object or $object->getFoo() returns null, then
null is returned, triggering the nil coalescing operator and resulting in a default empty array.
NOTE: This operator only handles null cases, i.e- if any of the methods above are
called upon an object that doesn't have them, then an error is thrown as normal.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=75017&edit=1