Error Call to Member Function get on null II

Preventing the "Error: Call to a member function get on null" with a sanity check.

In the last article, we saw what causes the "Call to Member Function get on null" in MODX. In this one, we'll see a way to prevent it.

MODX logo

In the previous article, we saw some code that's guaranteed to throw that error when we call get() on a retrieved MODX object without first checking to make sure we retrieved it. Here's one possible way to prevent that error.

A Solution

In the code below, we'll check the $parentObject variable to make sure it's not null:

$docs = $modx->getCollection('modResource');
foreach ($docs as $doc) {
    $parentId = $doc->get('parent');
    $parentObject = $modx->getObject('modResource', $parentId);
    // or $parentObject = $doc->getOne('Parent');
    if ($parentObject !== null) {
        $output .= '<li>' . $parentObject->get('pagetitle') . '</li>';
    } else {
        /* Resource has no parent --
           Do something else or do nothing */

return $output;

Speeding Things Up

The code above is somewhat inefficient. It attempts to get the parent of every resource, whether it has one or not. That's a waste of time. In the next article, we'll look at how to skip that action when we know it won't be successful

Coming Up

In the next article, we'll look at a more efficient way to prevent the error

Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)

Comments (0)

Please login to comment.