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, email@example.com
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/isset_ternary
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).
?: operator is overloaded, such that if the first operand 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 is used, which performs a falsiness check, existing code using the
?: operator should function the same. However, now no
E_NOTICE will be raised if the variable does not exist. While this should not affect most applications, it might affect some applications using custom error handlers, so this is a minor backwards-compatibility break and targets a major version.
Proposed PHP Version(s)
This proposed for the next PHP x, which at the time of this writing would be PHP 7.
None I'm aware of.
Unaffected PHP Functionality
The behaviour of the long-form ternary operator,
$a ? $b : $c,
empty are unaffected. Where the expression is not compatible with
isset, the existing behaviour continues to be used.
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
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
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.
Keep this updated with features that were discussed on the mail lists.