לסדר 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 הוא מחרוזת ריקה, false מוחזר.

השאר הערות אם יש הבהרות או תוספות למדריך זה.

כחובב טכנולוגיה, אני כותב בשמחה ב- 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 
השאירו תגובה