|  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
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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
37 - 9 = ?
Subscribe to this entry?

 [2017-08-01 13:15 UTC] php at haravikk dot me
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.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2017-08-01 17:15 UTC]
-Package: PHP Language Specification +Package: *General Issues
 [2017-08-02 17:21 UTC]
-Status: Open +Status: Duplicate -Assigned To: +Assigned To: cmb
 [2017-08-02 17:21 UTC]
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] <>
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Mon Aug 26 09:01:26 2019 UTC