Error call to member function get on null

What causes the "Call to a member function get() on null" error

In the last article, we saw how to preserve formatting when pasting text in PhpStorm. In this series of articles, we'll look at a common error in MODX, the most likely cause, and how to prevent it.

MODX logo

The Error

If you use MODX and write some of your own PHP code, you've likely seen this error somewhere along the line:

Error: Call to a member function get() on null

Depending on where the error occurs, you may also see a reference to a file and a line number.

The Cause

While I hesitate to use qualifiers like "always" and "never," every time I've seen this error, it has the same cause. It happens when the code has tried to retrieve a MODX object and failed, then tried to access a field of the object without checking to see if the object has really been retrieved.

Code like the following example is, by far, the most common cause of this error:

$docs = $modx->getCollection('modResource');
foreach ($docs as $doc) {
    $parentId = $doc->get('parent');
    $parentObject = $modx->getObject('modResource', $parentId);
    // or $parentObject = $doc->getOne('Parent');
    /* no error so far */
    $output .= '<li>' . $parentObject->get('pagetitle') . '</li>';

return $output;

Can you see why the code above is guaranteed to throw the error? First, it gets every resource on the site, then it gets the each resource's parent. Finally, it gets the parent's pagetitle with get().

What's wrong with that? Some of the resources will be at the root of the site and will have no parent! Their parent field contains a 0. Since no resource has 0 for an ID, the getObject() call (or the getOne() call) will fail and return null. That means the $parentObject variable will contain null. When we try to call $parentObject->get('pagetitle'), PHP complains that we're trying to call get() on null.

In the next article, we'll look at how to prevent this error.

Coming Up

In the next article, we'll look at one method for preventing 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.