This is an old revision of the document!
PHP RFC: Implicit isset() in Shorthand Ternary Operator
- Version: 0.1
- Date: 2014-09-06
- Author: Andrea Faulds, ajf@ajf.me
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/isset_ternary
Introduction
PHP is a web-focussed programming language, so processing user data is a frequent activity. In such processing it is common to check for something's existence, and if it doesn't exist, use a default value. Yet the simplest way to do this, something along the lines of isset($_GET['mykey']) ? $_GET['mykey'] : “”
, is unnecessarily cumbersome. The short ternary operator, ?:
provides a way to do this much more conveniently: $_GET['mykey'] ? “”
. However, this is not good practise, as if the value does not exist it will raise an `E_NOTICE`. Because of these issues, some sort of ifsetor() operator or a modification to ?:
's behaviour to make this common pattern easier has been a frequent request (See References).
Proposal
The ?:
operator is overloaded, such that if the first operand is can be used with isset
, an implicit isset
is performed alongside the truthiness check. This means the $_GET['mykey'] ?: “”
shorthand is completely safe and will not raise an E_NOTICE.
Internally this is actually implemented by rewriting the expression within the compiler from $a ?: $b
to empty($a) ? $b : $a
. This avoids introducing any new opcodes and allows us to leverage the existing infrastructure in place for empty
.
Backwards-compatibility considerations
Because empty
is used, which performs a falsiness check, all existing code using the ?:
operator continues to function identically, except that no E_NOTICE
will be raised if the variable does not exist.
Proposed PHP Version(s)
This proposed for the next PHP x, which at the time of this writing would be PHP 7.
Open Issues
None I'm aware of.
Unaffected PHP Functionality
The behaviour of the long-form ternary operator, $a ? $b : $c
, isset
and empty
are unaffected. Where the expression is not compatible with isset
, the existing behaviour continues to be used.
Future Scope
None I can think of currently.
Proposed Voting Choices
As this is a language change, a 2/3 majority is required. A straight Yes/No vote would be held.
Patches and Tests
A pull request with a working implementation and test, targeting master, is here: https://github.com/php/php-src/pull/809
Implementation
After the project is implemented, this section should contain
- the version(s) it was merged to
- a link to the git commit(s)
- a link to the PHP manual entry for the feature
References
There have been several previous discussions and proposals about adding an ifsetor operator with similar behaviour, or changing the behaviour of ?:
, indeed there has been at least one each year:
This list is quite probably incomplete.
Rejected Features
Keep this updated with features that were discussed on the mail lists.