现在我们来看看函式的一些更神奇的属性,其中包括使用可变参数个数的方法、让函式能够修改传入变数的方法,以及让函式成为资料使用的法方。
这一节的内容是本章最具挑战性的一节,它只适合具有冒险精神、求知欲极强或经验丰富的程序设计师。
可变参数个数
在依据情况呼叫传入函式时,知道实际参数数量是很有用的,在PHP中有三种可能的方式处理,其中一个只能在PHP4使用:
1. 定义带有预设参数的函式,当函式在呼叫中遗漏任何参数时,它都会用预设值来代替,不会显示警告资讯。
2. 使用阵列参数存放这些值,由呼叫的程序码中负责包装这个阵列,函式本体必须适当地将其中的资料分离。
3. 使用PHP4中的可变参数函式(func_num_args()、func_get_arg()和 func_get_args())。
预设参数
为了定义带有预设参数的函式,只需把形式参数变成指定运算式即可。如果实际呼叫时的参数比定义时的形式参数少,PHP会拿形式参数和实际参数进行比对匹配,直到用完为止,然后就使用预设的指定来填满其余参数。
例如,下面的函式中的变数都有是用预设值定义的:
function tour_guide($city = “Gotham City”,
$desc = “vast metropolis”,
$how_many = “dozens”,
$of_what = “costumed villains”)
{
print(“$city is a $desc filled with
$how_many of $of_what.< BR >”);
}
tour_guide();
tour_guide(“Chicago”);
tour_guide(“Chicago”,“wonderful city”);
tour_guide(“Chicago”,“wonderful city”,
“teeming millions”);
tour_guide(“Chicago”,“wonderful city”,
“teeming millions”,
“gruff people with hearts of
gold and hard-luck stories to tell”);
浏览器会输出类似下面的结果,句中的换行符号由所用浏览器决定:
Gotham City is a great metropolis filled with dozens of costumed villains.
Chicago is a great metropolis filled with dozens of costumed villains.
Chicago is a wonderful city filled with dozens of costumed villains.
Chicago is a wonderful city filled with teeming millions of costumed villains.
Chicago is a wonderful city filled with teeming millions of gruff people whit hearts of gold and hard-luck stories to tell.
预设参数的主要限制是,实际参数到形式参数的匹配是由两者的依序比对确定的,先到先服务。因而不能乱用预设参数的设定,以致最后出一堆问题而不自知。
用阵列替代多个参数
如果对多个参数的弹性不怎么满意,可以使用阵列来当成沟通手段,这样可绕过整个参数计数问题。
下面的例子就是使用这个策略,另外还用了几个小技巧,如三元运算子(在第七章中介绍过)和关联阵列(在第六章中提不定期,在第十一章中才会全面讲解):
function tour_brochure($info_array)
{
$city =
IsSet ($info_array[?city?])?
$info_array[?city?]:“Gotham City”;
$desc =
IsSet ($info_array[?city?])?
$info_array[?desc?]:“great metroprlis”;
$how_many =
IsSet ($info_array[?how_many?])?
$info_array[?how_many?]:“dozens”;
$of_what
IsSet ($info_array[?of_what?])?
$info_array[?of_what?]:“costumed villains”;
print(“$city is a $desc filled with
$how_many of $of_what.< BR >”);
}
这个函式检查将传入的阵列参数与特定字符串相隔的四种不同的值进行比较,使用三元条件运算子「?」,区域变数被指定为传入的值(如果已经被储存在阵列中),不然就是以预设值指定。现在,我们尝试用两个不同的阵列呼叫这个函式:
tur_brochure(array()); //空阵列
$tour_info =
aray(?city?=>?Cozumel?,
?desc?=>?destination getaway?,
‘of_what’= >‘sandy beaches’);
tur_brochure($tour_info);
在这个例子中,我们首先用空阵列(对应于无参数)
PHP学习宝典-第八章(二)

评论 (0) 