[php-src] Issue #8312: Add boolean assignment operators
| From: | KapitanOczywisty | Date: | Thu, 07 Apr 2022 13:43:57 +0000 |
| Subject: | [php-src] Issue #8312: Add boolean assignment operators | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-240750@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/8312
Comment Author: KapitanOczywisty
> I don't see a clear benefit to have these operators (and apparently, most other languages
> which have the logical operators and combined assignment operators do not either)
@cmb69 Beside shorter syntax, there are 2 more "benefits" from using
a ||= b
instead of a = a || b:
1. Setter is only called when not short-circuiting, this is similar to a || (a = b):
```php
new class
{
private array $data = ['foo' => true, 'bar' => false,];
function __construct()
{
$this->foo ||= true;
assert($this->data['foo'] === true);
$this->bar ||= false;
assert($this->data['bar'] === false);
}
function __get(string $name): bool
{
echo "Getter called for {$name}\n";
return $this->data[$name];
}
function __set(string $name, bool $value): void
{
echo "Setter called for {$name}\n";
$this->data[$name] = $value;
}
};
```
should be expected:
```
Getter called for foo
Getter called for bar
Setter called for bar
```
https://3v4l.org/LJp09
2. it's easier to use with incrementing keys:
```php
$array = [false, false, false];
$key = 0;
$array[$key++] ||= true;
$array[++$key] ||= true;
assert($array === [true, false, true]);
```
https://3v4l.org/FGBjj