I was happy coding until I wrote a code like this (in PHP 8.2):
if (!$a = false) {
echo '$a is false';
}
This snippet will print $a is false as expected. But according to the PHP documentation, the ! operator has greater precedence over the = operator, so that should be interpreted as (!$a) = null which I know is wrong, but hence my question: why? Is there a "hack" to allow this? Do I’m missing some documentation?
It make sense with instanceof:
$object = 'foo';
if (!$object instanceof SomeUnexistentClass) {
echo '$object is not instance of SomeUnexistentClass)';
}
That code will execute the echo because instanceof has greater precedence over the ! operator. So why the former code is valid?
>Solution :
There’s a note in the docs:
Although
=has a lower precedence than most other operators, PHP will still allow expressions similar to the following:if (!$a = foo()), in which case the return value offoo()is put into$a.