Would anyone know how we can rewrite the following function to be compatible and work with PHP 8?
function wpsc_have_shipping_quote() {
$has_quote = false;
global $wpsc_cart;
if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ) > 0 ) {
$has_quote = true;
}
return $has_quote;
}
CodePudding user response:
You don't have to count the array just to see if it has anything in it. When you use ||, the values being compared will be converted to booleans, and shipping_quotes will evaluate to false whether it is an empty array or a null.
function wpsc_have_shipping_quote() {
global $wpsc_cart;
return $wpsc_cart->shipping_quote_count || $wpsc_cart->shipping_quotes;
}
This should work in any PHP version.
CodePudding user response:
Andy. Kind regards.
In PHP 8. , count() does not accept null values anymore, it was already throwing warnings since PHP 7.2 if I recall correctly. Therefore the code is failing exactly here:
count( $wpsc_cart->shipping_quotes ) > 0
because in some situations $wpsc_cart->shipping_quotes may be null (it was not set).
You can use the new PHP 8 null coalescing to check if the value is null, and if it is null, you can provide an empty array []. So change the line:
if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ) > 0 ) {
To:
if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ?? [] ) > 0 ) {
