php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #75017 Nullable Method Calling
Submitted: 2017-08-01 13:15 UTC Modified: 2017-08-02 17:21 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: php at haravikk dot me Assigned: cmb (profile)
Status: Duplicate Package: *General Issues
PHP Version: Next Major Version OS:
Private report: No CVE-ID: None
 [2017-08-01 13:15 UTC] 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.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-08-01 17:15 UTC] stas@php.net
-Package: PHP Language Specification +Package: *General Issues
 [2017-08-02 17:21 UTC] cmb@php.net
-Status: Open +Status: Duplicate -Assigned To: +Assigned To: cmb
 [2017-08-02 17:21 UTC] cmb@php.net
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>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 03:01:27 2024 UTC