Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting PHP syntax: an 'implied if'?

I came across this interesting line in the default index.php file for a Zend Framework project:

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

It seems to be saying "If APPLICATION_PATH is not defined, then go on and define it..."

I'm not aware of this control structure in PHP. It's almost like an 'implied if' or 'if/else'. Can anyone help me out on this?

like image 895
DatsunBing Avatar asked Feb 03 '11 01:02

DatsunBing


2 Answers

It is not a control structure - it is just how || works. If first operand was evaluated to true - then second is not being evaluated at all.

http://php.net/manual/en/language.operators.logical.php --- look at the first 4 lines of the sample.

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());
like image 153
zerkms Avatar answered Nov 05 '22 08:11

zerkms


|| is a short-circuiting operator. If the left-hand operand is true, the expression as a whole must be true, so it won't bother evaluating the right-hand operand. You can use && in a reverse manner; if the left-hand operand is false, the expression as a whole must be false, so the right-hand operand won't be evaluated.

This is a rather idiomatic way to do things in some other languages. I'd usually prefer an explicit if in PHP though for this case.

like image 4
deceze Avatar answered Nov 05 '22 08:11

deceze