Anonymous Anonymous - 6 days ago 6
PHP Question

What's the most concise syntax to check chained return values in PHP?

If I need to access a value at the end of a chain of getters like this:

$employeeFirstName = $company->getEmployee()
->getName()
->getFirstName()
->getSomethingElse()
->getEtc();


If name, first name, something else or etc are null subsequent getter calls will throw an exception, so it's common practice to see null checking like this:

if($company->getEmployee()
&& $company->getEmployee()->getName()
&& $company->getEmployee()->getName()->getFirstName()
&& $company->getEmployee()->getName()->getFirstName()->getSomethingElse()
&& $company->getEmployee()->getName()->getFirstName()->getSomethingElse()->getEtc()
) {
// It's safe to use the value of getEtc()
}


Is there a more concise/reader-friendly way of null-checking chained get methods like this?

Answer

If it's supposed to be a fluent API, none of these methods should return null and should instead throw some defined exception. That enables you to write code like this:

try {
    $foo = $bar->baz()->quux()->blarg()...;
} catch (FooBarBazException $e) {
    $foo = null;
}

If the API is not supposed to be fluent, you should write it step by step with explicit success checks for each step which may return null:

$baz = $foo->bar()->baz();
if (!$baz) {
    return false;  // or whatever
}

$quux = $baz->quux();
if (!$quux) {
    ...
}

...

Repeatedly calling each method with a longer and longer chain is a waste of resources and hard to read.

Comments