Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clarify on PHP operators precedence ! and =

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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 of foo() is put into $a.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading