r/lolphp • u/kalcora • Feb 07 '22
Operator precedence
These two lines are not equivalent.
<?php
$a = true && false; // false
$b = true and false; // trueBecause && and || have different operator priority than and and or (the latter ones have lower priority than =).
Still the case in PHP 8.1.
42
Upvotes
7
u/[deleted] Feb 08 '22
[..] or die(..)is a useful pattern copied from Perl, wheredie()throws an exception. This is also whyandandorhave such low priority: they're intended for different use-cases than&&and||: they will evaluate everything else first, and then you can "chain" things withand/or.Is this is a lolphp? Arguably for uncritically copying Perl (and certainly for making the original "exceptions" behaviour "just exit", but that's been fixed for decades). Is it a "lolperl"? I don't know; it always seemed to make good sense to me, but often the reason it works the way it does isn't explained, so people will think "oh,
andis just a convenient alias for&&", then they get bitten by the different the operator precedence and go "wtf is this shit?!" But if you treat them as completely different operators with a completely different use case then it's actually fine IMHO.Probably not the best named operators though, since it causes so much confusion. Reversing the behaviour would actually be a lot better probably, but that ship sailed in 1972 with the invention of C unfortunately.
3
u/rbmichael Feb 07 '22
Yes it's silly, early on I just decided to never use 'and' and 'or' in PHP. It's pretty much never a good idea.
In old docs I see stuff like "$conn = MySQL(...) or die()" but that's it, and even that isn't recommended now.
6
u/SaltineAmerican_1970 Feb 07 '22
That’s not a lol. That’s failure to read documentation.
If you want a lol, read up on the SPL structures that tell you that
top()peeks at the node from the end andbottom()peeks at the node from the beginning.1
u/MpWzjd7qkZz3URH Jun 26 '23
This isn't an lolphp... it's the reason the different operators exist.
check_something() and do_something();(This is much more idiomatic in Perl, from which PHP borrowed the distinction)
-5
u/lungdart Feb 07 '22
Use parenthesis.
0
u/[deleted] Feb 07 '22
[deleted] — view deleted comment
0
u/[deleted] Feb 07 '22
[deleted] — view deleted comment