Consider the following (simplified to the bare bones):
abstract class Validator {
public function __construct($data = null)
{
$this->data = $data ?: Input::all();
}
}
$validation = new PageValidator($data);
'Input::all' is returning an array. $data is also an array.
The bit I am struggling with is:
$this->data = $data ?: Input::all();
I think it is essentially doing this:
if(!$data) {
$this->data = Input::all();
} else {
$this->data = $data;
};
But I don't really understand how?
It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);
” and “==!” in PHP. !== Operator: It is called as non-identical operator. It returns true if operands are not equal, or they are not of the same type.
Most of the time, they are about the same speed and you don't need to care.
The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
It's a feature of PHP 5.3 and above:
The ternary operator now has a shorthand form:
?:
.
Your understanding of the ternary operator is correct.
The exact syntax you've shown that omits the middle part of the operator was a feature added in PHP 5.3:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
The full expression, without omission, is:
$this->data = $data ? $data : Input::all();
Which translates to what you've assumed:
if($data) {
$this->data = $data;
} else {
$this->data = Input::all();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With