面对 PHP 8 警告:尝试读取 null 上的属性"query"



在运行PHP 8时获得这段代码的PHP警告:

function wpsc_body_class( $classes ) {
global $wp_query, $wpsc_query;
$post_id = get_the_ID();
if ( $post_id ) {
$page_url = get_permalink( $post_id );
// If on a product or category page...
if ( get_option( 'product_list_url' ) == $page_url || get_post_type( $post_id ) === 'wpsc-product' ) {
$classes[] = 'wp-e-commerce';
if ( ! is_array( $wpsc_query->query ) ) {
$classes[] = 'wpsc-home';
}
if ( wpsc_is_single_product() ) {
$object    = $wp_query->get_queried_object();
$classes[] = 'wpsc-single-product';
if ( absint( $object->ID ) > 0 ) {
$classes[] = 'wpsc-single-product-' . absint( $object->ID );
}
}
if ( wpsc_is_in_category() && ! wpsc_is_single_product() ) {
$classes[]  = 'wpsc-category';
$tax_object = $wp_query->get_queried_object();
$classes[]  = 'wpsc-category-' . esc_attr( $tax_object->slug );
}
if ( wpsc_is_in_tag() && ! wpsc_is_single_product() ) {
$classes[]  = 'wpsc-tag';
$tax_object = $wp_query->get_queried_object();
$classes[]  = 'wpsc-tag-' . esc_attr( $tax_object->slug );
}
}
$page_url = set_url_scheme( $page_url, 'relative' );
// If viewing the shopping cart...
if ( set_url_scheme( get_option( 'shopping_cart_url' ), 'relative' ) === $page_url ) {
$classes[] = 'wp-e-commerce';
$classes[] = 'wpsc-shopping-cart';
}
// If viewing the transaction...
if ( set_url_scheme( get_option( 'transact_url' ), 'relative' ) === $page_url ) {
$classes[] = 'wp-e-commerce';
$classes[] = 'wpsc-transaction-details';
}
// If viewing your account...
if ( set_url_scheme( get_option( 'user_account_url' ), 'relative' ) === $page_url ) {
$classes[] = 'wp-e-commerce';
$classes[] = 'wpsc-user-account';
}
}
return $classes;

}

指向这行代码的错误:

if ( ! is_array( $wpsc_query->query ) ) {

寻找解决此问题的最佳方法,并更改此代码,以克服php 8试图读取属性"query"的警告。在零。

您应该首先检查查询方法是否存在,并将该检查添加到if语句中,如下所示:

编辑:更新答案检查null

$queryMethodExists = method_exists($wpsc_query, 'query');
if (
$wpsc_query === null 
|| ($queryMethodExists && ! is_array( $wpsc_query->query ))
) {
$classes[] = 'wpsc-home';
}

相关内容

  • 没有找到相关文章

最新更新