PHP Or operator with function

Issue

I’ve seen this code: defined( 'ABSPATH' ) || exit;

My understanding is that the OR operator returns true if one of them is true. But in this case, exit is a function rather than an assessment to be tested. So is this means that if defined( 'ABSPATH' ) is false, then execute the exit? Why it will execute if it’s false?

Solution

This is a total guess on my part but my understanding is that this is taking advantage of PHP’s lazy evaluation processing. When it encounters values separated by || it will stop evaluating after the first one is true.

For example, the final false will not be checked since the preceding expression is true.

if (false || true || false) { ... }

So, defined( 'ABSPATH' ) || exit; will first evaluate defined( 'ABSPATH' ) and if it is true, it will skip the 2nd expression and the program will continue. Only if it is false will it execute the final expression exit and terminate the program.

Answered By – waterloomatt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published