修复PHP警告:sizeof():参数必须是实现可计数的数组或对象

许多出现的PHP错误 WordPress Plugins 很长一段时间没有更新或与新版本的PHP不兼容。 PHP警告:sizeof():参数必须是实现可数的数组或对象。

在我们的情况下,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

De Ce Apare Eroarea php警告:sizeof():参数必须是实现可数的数组或对象?

生成此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;
	
}

此更改首先检查是否 $crosssells 是一个 array 使用该功能 is_array() 否则返回 false

如果 $crosssells 是一个 array,使用该功能 count() 确定项目数量 array。如果项目数为零或 $crosssells 它是一个真空字符串,它返回false。

如果要对本教程进行澄清或完成,请发表评论。

从2006年开始,我对技术充满热情,在StealthSetts.com上写作。我在操作系统方面拥有丰富的经验:MacOS,Windows和Linux,以及编程语言和博客平台(WordPress)和在线商店(WooCommerce,Magento,Magento,Presashop)。

您的教程,有用的提示和新闻。 修复PHP警告:sizeof():参数必须是实现可计数的数组或对象
发表评论