I have written a helper function for multilevel chaining. Let's say you want to do something like $obj1->obj2->obj3->obj4
, my helper function returns empty string whenever one of the tiers is not defined or null, so instead of $obj1->obj2->obj3->obj4
you my use MyUtils::nested($obj1, 'obj2', 'obj3', 'obj4')
. Also using this helper method will not produce any notices or errors. Syntactically it is not the best, but practically very comfortable.
class MyUtils
{
// for $obj1->obj2->obj3: MyUtils::nested($obj1, 'obj2', 'obj3')
// returns '' if some of tiers is null
public static function nested($obj1, ...$tiers)
{
if (!isset($obj1)) return '';
$a = $obj1;
for($i = 0; $i < count($tiers); $i++){
if (isset($a->{$tiers[$i]})) {
$a = $a->{$tiers[$i]};
} else {
return '';
}
}
return $a;
}
}
__get
), whereas bothisset
and the null coalescing operator??
will. – Mccleary