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;
}
doqgmui
  • 49
  • 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. – Ulrich Eckhardt Oct 30 '22 at 12:29
  • Does this answer your question? [PHP Lazy Boolean Evaluation](https://stackoverflow.com/questions/4216754/php-lazy-boolean-evaluation) – Progman Oct 30 '22 at 12:30
  • Hi, "evaluate" means it will run the command/function/code before turning it into a boolean value? – doqgmui Oct 30 '22 at 12:33
  • `a || b` is different from `a && b` – nice_dev Oct 30 '22 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](https://3v4l.org/h7apJ) which are also valid – Chris Haas Oct 30 '22 at 13:22

0 Answers0