PHP RFC: ?= (check and set) operator
- Version: 0.1
- Date: 2018-07-06
- Author: Jefersson Nathan, firstname.lastname@example.org
- Status: Draft
- First Published at: http://wiki.php.net/rfc/check_and_set
Combined assignment operators have been around since 1970's, appearing first in the C Programming Language. For example, `$x = $x + 3` can be shortened to `$x += 3`.
With PHP being a web focused language, the `?:` ternary operator is often used to check something's existence like `$this->obj = $obj ?: new \stdClass;` However, because variable names are often much longer than `$username`, the use of `?:` for self assignment creates repeated code, like:
$this->requestDataFomUserWasFound = $this->requestDataFomUserWasFound ?: 'value';
It is also intuitive to use combined assignment operator null ternary checking for self assignment.
Despite `?:` operator being a comparison operator, ternary equal or `?=` operator is an assignment operator. If the left parameter is null, assigns the value of the right paramater to the left one. If the value is not null, nothing is made.
// The folloving lines are doing the same $this->requestDataFromUserWasFound = $this->requestDataFromUserWasFound ?: 'value'; // Instead of repeating variables with long names, the equal check and set operator is used $this->requestDataFromUserWasFound ?= 'value';
The value of right-hand parameter is copied if the left-hand parameter is null-like.
Proposed PHP Version(s)
This proposed for the next PHP 7.x.
Patches and Tests
A pull request with a working implementation is on the way.