PHP中的一些函数传参方式和C语言很像,比如传值方式和传址方式。
还有一些特有的传参方式,此处说明。
- 默认参数:在函数声明时给参数赋值,而且此默认参数只能在最后,调用时可不传递任何参数(若只有默认参数的情况下)
e.g.:
<?php
function person($age,$name = "php"){
echo "我的名字:",$name;
echo "<br />";
echo "我的年龄:",$age;
}
person(23); 输出:
我的名字:php
我的年龄:23而将$name = "php" 放在$age前面的时候,系统将会报错。
- 可变参数:一个函数可能需要可个可变数目的参数。在php中,提供了三个函数用于检索函数中所传递的参数。func_get_args()返回一个提供提供给函数的所有参数的数组;func_num_args()返回提供给函数的参数数目;func_get_arg()返回一个来自参数的特定参数。具体如下:
$array = func_get_args();
$count = func_num_args();
$value = func_get_arg();
e.g.:
<?php
function countList()
{
if(func_num_args == 0)
{
return false;
}
else
{
$count = 0;
for($i = 0; $i<func_num_args();$i++)
{
$count += func_get_arg($i);
}
return $count;
}
}
echo countList(1,5,9); //输出 15
?>- 遗漏参数:当调用函数时,可以传递任意个参数给函数。当函数必要的参数没有i被传递时,此参数值是空,并且PHP会为每个遗漏的参数发出警告:
function takesTwo($a,$b)
{
if(isset($a))
{
echo "a is set \n";
}
if(isset($b))
{
echo "b is set \n";
}
}
echo "with two arguments: \n"
takesTwo(1,2);
echo "with one argument: \n"
takesTwo(1);输出:with two arguments:
a is set
b is set
with one argument:
warning : missing argument ...
a is set- 可变函数:使用可变变量,可以基于变量的值调用函数:
switch($which) { case 'first': first(); break; case 'second': second(); break; case 'third': third(); break; } //调用时必须在变量后加上圆括号 $which = 'first'; $which();//调用first()
其实可以把这个可变函数和java/C++中的接口和多态结合起来理解,只不过后者是一个抽象函数,每次使用都需要重写,而前者只需要改变函数名,语法上加上圆括号便可直接调用。//example2 <?php class Foo { function Variable() { $name = 'Bar'; $this->$name(); // This calls the Bar() method } function Bar() { echo "This is Bar"; } } $foo = new Foo(); $funcname = "Variable"; $foo->$funcname(); // This calls $foo->Variable() ?>
注:echo(),isset(),print()等系统函数不可被当作变量使用。 - 匿名函数:又叫闭包函数,允许临时建立一个没有指定名称的函数,最经常用作回调函数参数的值。
可以直接赋值给变量:
也可以在函数中用作返回量使用:$closefunc = function() { ...... }
需要注意的是,在匿名函数内的变量的用法不同于全局变量,在匿名函数内的变量是一个闭包变量,另外,被调用闭包的作用域不必是相同的。function closureFunc4(){ $num = 1; $func = function($str) use($num){ echo $num; echo "\n"; echo $str; }; return $func; } $func = closureFunc4(); $func("hello, closure4"); //输出: //1 //hello, closure4
1793

被折叠的 条评论
为什么被折叠?



