PHP Ternary Operator checks if a variable contains something?

Consider the following (simplified to bare bone):

abstract class Validator { public function __construct($data = null) { $this->data = $data ?: Input::all(); } } $validation = new PageValidator($data); 

'Input :: all' returns an array. $ data is also an array.

The bit I'm struggling with is:

 $this->data = $data ?: Input::all(); 

I think this basically does this:

  if(!$data) { $this->data = Input::all(); } else { $this->data = $data; }; 

But I really do not understand how?

+6
source share
4 answers

This is a function for PHP 5.3 and higher:

Now the ternary operator has an abbreviated form: ?: .

+6
source

Your understanding of the thermal operator is correct.

The exact syntax you showed that omits the middle part of the statement is a function added in PHP 5.3:

With PHP 5.3, you can exclude the middle part of the ternary operator. Expression expr1 ?: Expr3 returns expr1 if expr1 is TRUE and expr3 otherwise.

Full expression without omission:

 $this->data = $data ? $data : Input::all(); 

This means that you assumed:

 if($data) { $this->data = $data; } else { $this->data = Input::all(); } 
+5
source

?: is an abbreviation for triple operator since PHP 5.3

So ?: Looks like || in javascript in the following case:

var myVar = var1 || var2

If the value of var1 evaluates to true, myVar will be that, otherwise var2 .

Notes:

0 , '' , false and null evaluate to false, so if you have the following:

 $data = 0; $this->data = $data ?: 'someVal'; echo $this->data; 

As a result, you will get "someVal" .

In this case, use isset or empty .

+2
source

try this form:

 $this->data = $data ? $data : Input::all(); 
0
source

Source: https://habr.com/ru/post/950928/


All Articles