Switching from PHP7.4 to PHP8.1 Fatal error: Uncaught Error: Attempt to assign property "posts" on null
in (Templatefile) on line 93 98 224 232

Viewed 25

Trying to update a WordPress site from PHP7.4 to 8.1 and I am getting these errors

Fatal error: Uncaught Error: Attempt to assign property "posts" on null
in TEMPLATEFILE on line 93

Line 93 
    $query_txt_ref->posts = array();
Line 98
    $query_book->posts = array();
Line 224
    $query_txt_ref_others->posts = array();
Line 232
    $query_others->posts = array();

Was working in 7.4 but not sure how to go about changing it. Would anyone be able to give me pointers on how to change this?

Here's a few more lines for reference.

    add_filter('posts_where', 'where_text_refrence');
    add_filter('posts_join','join_text_refrence');
    $query_txt_ref->posts = array();
    $query_txt_ref = new WP_Query($args_daily_devotion_txt_ref);
    remove_filter('posts_where', 'where_text_refrence');
    remove_filter('posts_join', 'join_text_refrence');

    $query_book->posts = array();
    add_filter('posts_where', 'where_botb_tags');
    $query_book = new WP_Query($args_daily_devotion);
    remove_filter('posts_where', 'where_botb_tags');
1 Answers

The ->foo syntax refers to object properties. Until PHP/8, when you tried to write a property in a variable that is null, PHP would automatically create an object for you:

$query_txt_ref = null;
$query_txt_ref->posts = array();
var_dump($query_txt_ref);
object(stdClass)#1 (1) {
  ["posts"]=>
  array(0) {
  }
}

PHP has warned about this for many years (first notice, then warning). Currently, you no longer get an object and a fatal error is thrown.

Demo

If you were relying on the object being initialised automatically, you need to be explicit now:

$query_txt_ref = new stdClass();
$query_txt_ref->posts = array();

If it was masking a bug, you need to fix it at the source. Find where $query_txt_ref is initialised and figure out why it's sometimes not an object. If it's something that can be expected to happen, you need to handle it:

if ($query_txt_ref === null) {
    // Do something
} else {
    $query_txt_ref->posts = array();
}

If it cannot possibly happen, the issue will be found somewhere before initialisation.

Related