1

This is just more of a "why does it work" and "why or why not use it" type question.

We all know PHP expressions using ternary operations

$var = (isset($i) ? true:false);

But in PHP something like the following works too. (It is not ternary, 3 parts, it is more of a binary operation, 2parts.)

$var = true;
isset($i) || $var = false;

Which may not be so practical :) but a more useful construction is

isset($i) || exit();

So the above (much better looking imo) would have the same result as

if(!isset($i)) exit();

But other than the common

defined('CONSTANT') || define('CONSTANT','FOO');

I rarely see this type of construct used in PHP. Why does this work? What is it called. Why is it not taught or used more. Are there cons to using it? And is there practical ways to use && in the same way?

skribe
  • 3,595
  • 4
  • 25
  • 36
  • FYI, `$var = (isset($i) ? true:false);` is just a convoluted synonym for `$var = isset($i);` – Álvaro González Jan 20 '17 at 09:31
  • 1
    it is called "logical or". and it is lazy - meaning: if the first part is true, there is *no need* to evaluate the second part, because the result always *will be* true. similar to and: the second part will only be evaluated if the first part is true. for more information: see **[the manual](https://secure.php.net/manual/en/language.operators.logical.php)** – Franz Gleichmann Jan 20 '17 at 09:35
  • @ Alvaro Right. it was a just an example of the ternary construction. – skribe Jan 20 '17 at 09:35
  • 1
    @skribe But, for some reason, many developers actually think that there are never enough parenthesis and booleans are never boolean enough ;-) – Álvaro González Jan 20 '17 at 09:39
  • @Álvaro That is unfortunately very true (correct (right (accurate (unerring (flawless))))). – deceze Jan 20 '17 at 09:43
  • 1
    @ÁlvaroGonzález preemptive parentheses prevent pesky priority problems ;) (although, in the given example, it *is* superfluous) – Franz Gleichmann Jan 20 '17 at 09:44

1 Answers1

1

This way of writing statements also exists in C, Perl and other languages, it plays with how the compiler evaluates statements chained with logical operators.

Imagine you have an expression if (a() or b()), then when a() returns true you don't have to evaluate b(), because the entire statement is true already. So b() is only called when a() is false. You can write this without the if, it still works the same way.

This shorthand is usually found like you described, to define default values or exit if a condition is not met.

fafl
  • 7,222
  • 3
  • 27
  • 50