固定 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable 

出现在许多地方的 PHP 错误 WordPress Plugins 长时间未更新或与较新版本的 PHP 不兼容。 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable.

在我们的场景中,PHP 错误发生在一个模块中 Cross Sell Product Display 为 WooCommerce.

FastCGI sent in stderr: "PHP message: PHP Warning:  sizeof(): Parameter must be an array or an object that implements Countable in /web/path/public_html/wp-content/plugins/cross-sell-product-display-for-woocommerce/templates.php on line 18

为什么会发生错误 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable ?

产生这个 PHP 错误的问题是函数 sizeof() 在 PHP 7.2 或更高版本中,如果给定的参数不是一个,则会产生此错误 array 或实现接口的对象 Countable.

所以这个错误经常出现在PHP版本更新之后。

如何解决 PHP 产生的错误 sizeof()?

最简单的方法是替换函数调用 sizeof() 通过函数调用 count().

对于那些使用旧版本模块的人 Cross Sell Product Display,解决方法很简单。 18 英寸系列的功能将被替换 templates.php.

function cdxfreewoocross_get_cross_sell_products($product_id=false){
	
	if($product_id ===false ){
		
		if(!is_product()){return false;}
		
		$product_id = (int)get_the_ID();
		if($product_id=='0'){return false;}
		
	}
	
	$crosssells = get_post_meta( $product_id, '_crosssell_ids',true);
	if ( sizeof($crosssells ) == 0  || $crosssells =='') { return false; }
	
	return $crosssells;
	
}

上面的代码在其中 sizeof() 将被替换为:

function cdxfreewoocross_get_cross_sell_products($product_id=false){
	
	if($product_id ===false ){
		
		if(!is_product()){return false;}
		
		$product_id = (int)get_the_ID();
		if($product_id=='0'){return false;}
		
	}
	
	$crosssells = get_post_meta( $product_id, '_crosssell_ids',true);
	if ( !is_array( $crosssells ) || count( $crosssells ) == 0  || $crosssells =='') { return false; }
	
	return $crosssells;
	
}

此修改首先检查是否 $crosssellsarray 使用函数 is_array() 否则返回 false.

的情况下 $crosssellsarray, 函数被使用 count() 确定元素的数量 array. 如果元素个数为零或 $crosssells 是一个空字符串,返回 false。

如果对本教程有任何澄清或补充,请发表评论。

作为科技爱好者,我从2006年开始在StealthSettings.com上愉快地撰写文章。我在操作系统方面有丰富的经验,包括macOS、Windows和Linux,还熟悉编程语言和博客平台(WordPress),以及在线商店平台(WooCommerce、Magento、PrestaShop)。

如何以 » WordPress » 固定 PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable 
发表评论