แก้ไขปัญหา 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;
	
}

การปรับเปลี่ยนนี้จะตรวจสอบก่อนว่า $crosssells เป็น array โดยใช้ฟังก์ชัน is_array() และมิฉะนั้นจะกลับมา false.

ในกรณีที่ $crosssells เป็น array, ฟังก์ชันถูกใช้ count() เพื่อกำหนดจำนวนองค์ประกอบใน array. หากจำนวนองค์ประกอบเป็นศูนย์หรือ $crosssells เป็นสตริงว่าง คืนค่าเท็จ

แสดงความคิดเห็นหากมีการชี้แจงหรือเพิ่มเติมในบทช่วยสอนนี้

เป็นคนรักเทคโนโลยี ฉันเขียนบทความด้วยความสุขบน StealthSettings.com ตั้งแต่ปี 2006 ฉันมีประสบการณ์ที่หลากหลายในระบบปฏิบัติการ: macOS, Windows, และ Linux, รวมถึงภาษาโปรแกรมและแพลตฟอร์มบล็อก (WordPress) และสำหรับร้านค้าออนไลน์ (WooCommerce, Magento, PrestaShop)

วิธีการ » WordPress » แก้ไขปัญหา PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable 
แสดงความคิดเห็น