DatsunBing
DatsunBing

Reputation: 9076

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?

Upvotes: 5

Views: 471

Answers (4)

deceze
deceze

Reputation: 522024

|| 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.

Upvotes: 4

Don Roby
Don Roby

Reputation: 41137

This is a short-circuiting evaluation of a boolean expression, which is indeed a way to accomplish something like an if-else.

Upvotes: 2

Mark Elliot
Mark Elliot

Reputation: 77034

Technically this is just some boolean expression that gets evaluated but throws away the result. It's using short-circuit logic to assure that the latter half of it is only run when the first half is false.

Similarly, you can capture the result:

$foo = false || true;  // $foo will contain true.

Upvotes: 2

zerkms
zerkms

Reputation: 254906

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());

Upvotes: 16

Related Questions