提问人:Andy 提问时间:1/17/2023 更新时间:1/18/2023 访问量:685
面对 PHP 8 警告:尝试读取 null 上的属性“query”
Facing PHP 8 Warning: Attempt to read property "query" on null
问:
在运行 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 ) ) {
寻找解决此问题的最佳方法,并更改此代码,以克服尝试读取 null 上的属性“query”的 php 8 警告。
答:
0赞
A. Pallis
1/17/2023
#1
您应该首先检查查询方法是否存在,并将该检查添加到您的 if 语句中,如下所示:
编辑:更新了答案以检查空值。
$queryMethodExists = method_exists($wpsc_query, 'query');
if (
$wpsc_query === null
|| ($queryMethodExists && ! is_array( $wpsc_query->query ))
) {
$classes[] = 'wpsc-home';
}
评论
0赞
Andy
1/17/2023
谢谢 A. Pallis。会尝试您的建议,并让您知道结果。
0赞
Andy
1/17/2023
尝试了上面的代码,但它导致了以下致命错误: PHP 致命错误:未捕获的 TypeError:method_exists():参数 #1 ($object_or_class) 必须是 object|string 类型,null 给出(与此代码行相关 $queryMethodExists = method_exists($wpsc_query, 'query');
0赞
A. Pallis
1/18/2023
您好@James,您还需要在 if 语句中对 null 进行额外检查。当我有机会时,我会编辑我的原始答案。
0赞
Andy
1/18/2023
谢谢 A.Pallis,非常感谢您为此付出的所有时间和帮助。已使用修改后的代码进行了更新,但仍然收到相同的PHP致命错误。
评论