&&can be used to safely extract the value of an object’s field, and will return null if either the object or the field has not been initialized
// returns null if param, param.object or param.object.field // have not been set field = param && param.object && param.object.field;
||can be used to set default values:
// set param to its default value param = param || defaultValue;
Does PHP allow this use of the logical operators as well?
r = a || b || c with:
$r = $a ?: $b ?: $c;
Regarding ‘ands’, something like:
$r = ($a && $a->foo) ? $a->foo->bar : null;
PHP logical operators do not return the value on any of their sides : they will always get you a boolean.
For instance, doing :
$result = $a && $b;
Will always make
$result contain a boolean :
false — and never
You can set up similar functionality using ternary operators.
<?php // prelim $object = new stdClass; $object->field = 10; $param = new stdClass; $param->object = $object; // ternary variant $field = !($param && $param->object)?: $param->object->field; echo $field,"\n"; // alternative to ANDing $field = get_object_vars( $param->object )["field"] ?? null; echo $field,"\n";
See live code
The “Elvis” operator “?:” only assigns the result to $field if the conditional expression is false. So, if $param exists as well as $param->object, then you have to use the NOT operator (“!”) in order to get the desired result.
You may also accomplish the objective of getting the field data without ANDing by utilizing the null coalescing operator (“??”) in PHP 7 in tandem with