I was going through operator precedence section of php.net and came across this example which says
$a = 1;
$b = null;
$c = isset($a) && isset($b);
$d = ( isset($a) and isset($b) );
$e = isset($a) and isset($b);
var_dump($a, $b, $c, $d, $e);
//Result:
int(1)
NULL
bool(false)
bool(false) <== I get this
bool(true) <== I do not get this
I use quite a lot of debugging and verbose print(_r) statements in my code to keep track of where I am in the code. So I use $debug and print_r($dataArray)
or $verbose and print "Updating dataArray\n"
as separate statements in between the code, allowing me to control these print(_r) statements. This comes from my BASH experience where I used to write lot of [[ $condition ]] && { #Do if true } || { #Do if false }
. In BASH, I knew they are short circuited and used this fact to write lot of simple one liners.
Now I am observing that lot of this practice(of writing $verbose and print
) is slowly creeping into my if
statements. I am aware this is NOT a recommended practice and can bite me in the back. However, I do want to master this skill as I enjoy writing such one liners and want to use it as my personal style.
So my question(s) is(are) :
&&
or and
) is short circuited ?&&
takes precedence over and
, but can someone exemplify this by mixing the short circuited operator feature/functionality/characteristic with operator precedence. (basically mix and match of precedence and short-circuiting)Kindly elaborate on both the short-circuiting as well as return value nature of the operators.
PS: 1. I hope associativity of these operators is same and intuitive, but if you know any quirks, please enlighten me.
PS: 2. If you still feel like warning me against the perils of such practice, kindly include examples.
EDIT : After changing my simple $var = mysql_(...) or die()
code by replacing or
with ||
, I discovered how annoying it can be to use the ||
and &&
operators instead of and
and or
. The code simply didn't work ! To my understanding, the former construct assigns a return value of TRUE
or FALSE
to $var
, which in turn make all sequential use of $var
to generate warning/error/unexpected behavior. The latter construct assigns result of mysql_(...)
to $var
first and then evaluates the compound of =
and die
.
This is a good lesson for me, I better 1. Start using PDO/mysqli and handle errors on my own 2. Think twice before writing something I called above as personal style.
//note to self : don't use experience of one scripting/interpretive language while writing code in another, each one is unique and has its own quirks and pitfalls, and thats just sad *sigh*
The code
$e = isset($a) and isset($b);
is parsed the same as
($e = isset($a)) and isset($b);
Therefore $e
, as determined by isset($a)
and the assignment, is true
- independent of evaluating isset($b)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With