0

I saw the plugin "WooCommerce" from WordPress is using the OR operator ( || ) to execute the exit command, below is the code:

defined( 'ABSPATH' ) || exit;

I understand that PHP is "lazy/short-circuit" and will not reach exit if the former is true. But I thought the boolean would always return a boolean value instead of being capable of executing a PHP command like exit? ( refer to the first user contributed note: https://www.php.net/manual/en/language.operators.logical.php )

I mean a||b both "a" and "b" are intended to be something to be tested, and not running a command like a|| // Do something?

Instead the below code is correct and understandable

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
5
  • 1
    a || b means first evaluate a and convert it to a boolean. Then, if the result is not true, evaluate b. In this case, evaluating b means "calling" exit, which doesn't return anything. Commented Oct 30, 2022 at 12:29
  • Does this answer your question? PHP Lazy Boolean Evaluation Commented Oct 30, 2022 at 12:30
  • Hi, "evaluate" means it will run the command/function/code before turning it into a boolean value? Commented Oct 30, 2022 at 12:33
  • a || b is different from a && b Commented Oct 30, 2022 at 12:40
  • 1
    Personally, even though I’ve been doing PHP for a long time, I prefer the syntax that you are suggesting. I recognize the syntax you are questioning but my brain doesn’t like the pattern. That said, (and leaving aside that exit is a language construct and not a direct function), that code is effectively the same as these which are also valid Commented Oct 30, 2022 at 13:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.