Operator priority is an important knowledge point that a programmer must understand and hold. let's take a look at the article on PHP operator priority. today we see
Operator priority is an important knowledge point that a programmer must understand and hold. let's take a look at the article on PHP operator priority. Today, we see a problem in Lao Wang's technical manual, the code is as follows:
What is output?
This question may be simple at first glance, but it is not easy to think carefully. if we say that Boolean and the previous part are due to priority issues, but if it is just a matter of priority, the result should be:
$ A = (100 & $ B) = 200
In fact, the result is indeed a high-priority & concession to the next priority =, let $ B = 200 first combined. the reason is that PHP does not fully comply with the definition of priority, which is also described in the PHP manual:
Note: 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 $.
In this design, I do not express my opinion. in C language, such similar statements are regarded as syntactic errors. PHP adopts this design, which may be due to historical reasons. curious students may wonder why. Previously, jayeeliu asked:
Hello laruence:
The code for a php operator priority is as follows:
$ T = 1 & $ tt = 2
According to the php operator, the priority should be
($ T = 1) & $ tt) = 2
This sequence is executed, but it should actually be
($ T = 1) & ($ tt = 2)
I don't quite understand it. In fact, it is simple. operator priority is a method of selecting protocol rules when there is a binary grammar. in the definition of PHP syntax analysis file, the instance code is as follows:
- Expr_without_variable:
- // A hidden rule exists, which is equivalent to T_BOOLEAN_AND becoming the "unary operator ".
- | Expr T_BOOLEAN_AND {zend_do_boolean_and_begin (& $1, & $2 TSRMLS_CC);} exp
Finally, by the way, PHP also defines T_LOGICAL_AND (and) and T_LOGICAL_OR (or) for T_BOOLEAN_AND. the priority of these two values is lower than the equal sign, so there will be, the following are typical examples of PHP tutorials:
$ Result = mysql_query (*) or die (mysql_error ());
Similarly, we can use or to implement the ternary operator (? The code is as follows:
$ Person = $ who or $ person = "laruence"; // equivalent to: $ person = empty ($ who )? "Laruence": $ who;
Integration direction
Operator
Left,
Left or
Left xor
Left and
Right print
Right = + =-= * =/=. = % = & = | = ^ = ~ = <=> =
Left? :
Left |
Left &&
Left |
Left ^
Left &
None =! ===! =
None <=> =
Left <>
Left + -.
Left */%
Right! ~ ++ -- (Int) (float) (string) (array) (object )@
Right [
No new