לפעמים אנחנו כותבים פונקציות שלא ידוע כמה פרמטרים יקבלו כשיפעילו אותם. דרך אחת היא לעשות את הפרמטר של הפונקציה למערך. דרך אחרת היא כמות משתנה של פרמטרים שדי קל לעשות.

פונקציה אחת בלבד מספיקה. היא בודקת אילו פרמטרים הועברו לפונקציה שלנו והופכת אותם למערך בעמצה (במקום שאנחנו נעביר לפונקציה מערך):
function cut_vegetables( /* nothing here */ )
{
// func_num_args returns the total number of parameters
echo 'totally ', func_num_args(), ' vegetables';
// func_get_args returns all the parameters as array
$vegetables = func_get_args();
print_r($vegetables);
}
cut_vegetables('tomato');
cut_vegetables('tomato', 'potato');
$onion = 'sliced onion';
cut_vegetables('tomato', 'potato', 'cucember', 5555, $onion);
{
// func_num_args returns the total number of parameters
echo 'totally ', func_num_args(), ' vegetables';
// func_get_args returns all the parameters as array
$vegetables = func_get_args();
print_r($vegetables);
}
cut_vegetables('tomato');
cut_vegetables('tomato', 'potato');
$onion = 'sliced onion';
cut_vegetables('tomato', 'potato', 'cucember', 5555, $onion);
אפשר לראות דוגמה חיה לשימוש ב func_get_args
תגובות לכתבה:
למה לא להעביר ARRAY וזהו?
כי זה הרבה יותר נוח...
יפה.
אני תמיד התבאסתי ליצור מערך כשצריך להעביר רק פרמטר אחד
func(array('param')); //x
יותר נחמד לי ככה:
func('param'); //x
אין passing by reference בדרך הזאת, נכון?