1

When upgrading our website to PHP 8.0, we are faced with the following error:

Warning: Trying to access array offset on value of type bool

This relates to the following line of code:

$meta_value = $meta_values[ $meta_tuple['object_id'] ];

Code for the whole function is:

function wpsc_get_meta( $meta_key, $object_type, $object_id = 0 ) {

    global $wpdb;

    $cache_object_id = $object_id = (int) $object_id;
    $meta_key = wpsc_sanitize_meta_key( $meta_key );

    $meta_tuple = compact( 'object_type', 'object_id', 'meta_key' );
    $meta_tuple = apply_filters( 'wpsc_get_meta', $meta_tuple );

    // Get cached meta
    $meta_value = wp_cache_get( $cache_object_id, $meta_tuple['object_type'] );

    // If not cached, get and cache all object meta
    if ( $meta_value === false ) {
        $meta_values = wpsc_update_meta_cache( $meta_tuple['object_type'], $meta_tuple['object_id'] );
        $meta_value = $meta_values[ $meta_tuple['object_id'] ];
    }

    if ( isset( $meta_value[ $meta_tuple['meta_key'] ] ) ) {
        return maybe_unserialize( $meta_value[ $meta_tuple['meta_key'] ] );
    }

    return '';
}

Any suggestions how we could fix the above code for PHP 8.0 compatibility?

Rolled back to PHP 7.4, and the warning disappears.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Andy
  • 23
  • 2
  • 7
  • 1
    In php8 types are more strict. So if you want to get rid of the message do `if ( is_array($meta_value) && isset( $meta_value[ $meta_tuple['meta_key'] ] ) ) {`. Because at this point `$meta_value` can actualy be an array or an bool. – Foobar Dec 20 '22 at 11:09
  • Would highly recommend that your [read the fabulous manual](https://www.php.net/manual/en/migration80.php) on the topic of upgrading to 8.x. Thoroughly. Then make a plan based on what you find in your code and how much of it there is. Be prepared to change your code and test all over again. – YvesLeBorg Dec 20 '22 at 11:26
  • Thank you for your input. Added your line of code after the following and the warnings have vanished. $meta_values = wpsc_update_meta_cache( $meta_tuple['object_type'], $meta_tuple['object_id'] ); – Andy Dec 20 '22 at 16:18

1 Answers1

0

You can change this

if ( isset( $meta_value[ $meta_tuple['meta_key'] ] ) ) {
    return maybe_unserialize($meta_value[$meta_tuple['meta_key']]);
}

to (see Null coalescing operator)

if ($meta_value[ $meta_tuple['meta_key']] ?? null)
   return maybe_unserialize($meta_value[$meta_tuple['meta_key']]);
}

or (old school)

if ( 
     is_array($meta_value)
     && isset( $meta_value[ $meta_tuple['meta_key'] ] ) 

) {
    return maybe_unserialize($meta_value[$meta_tuple['meta_key']]);
}
Foobar
  • 769
  • 1
  • 4