如何学习呢?可以从以下几个方面考虑
函数是如何定义的?区分大小写吗? 函数的参数是如何定义的? 函数是否支持重载? 函数的返回值是如何定义的。 函数有变量函数吗? 如果把上面的问题搞清楚了,相信函数你也就掌握了。还是一个个看吧。
函数是如何定义的?区分大小写吗? 首先函数对大小写不敏感。但是还是建议你采用和函数声明时的一样。
函数是如何定义的呢?语法可以为:
php
function func( $arg_1 , $arg_2 , , $arg_n )
{
echo example function.\n ;
return $retval ;
}
?>
其实和其他语言差不多。不过函数声明里不需要显式的说明返回类型。和javascript差不多。
那么是不是和c语言一样,函数先定义后使用呢?这个问题非常好。在php3中,确实需要这样,但是后期版本则没有限制了。
由于php存在函数种的函数或条件函数,所以这2种情况下需要先定义后使用,要是没有定义函数你却使用了,系统会出问题的。函数中的函数倒是和python有些类似。
条件函数的例子可以是:
1 php
2 $isrequired = true ;
3 if ( $isrequired )
4 {
5 function func( $op1 , $op2 )
6 {
7 return $op1 + $op2 ;
8 }
9 }
10 if ( $isrequired )
11 echo func(1,3)= . func( 1 , 3 );
12
13 function helloworld()
14 {
15 return hello,world ;
16 }
17 echo '
call function helloworld(): ' . helloworld();
18 ?>
输出结果为:
func( 1 , 3 ) = 4
call function helloworld() : hello , world
函数中的函数可以是:
1 php
2 function func()
3 {
4 function subfunc()
5 {
6 echo i don't exist until func() is called.\n ;
7 echo i have alrady made ;
8 }
9 }
10
11 /* we can't call subfunc() yet
12 since it doesn't exist. */
13
14 func();
15
16 /* now we can call subfunc(),
17 func()'s processesing has
18 made it accessable. */
19
20 subfunc();
21
22 ?>
输出结果是:
i don ' t exist until func() is called. i have alrady made
2. 函数的参数是如何定义的?
和通常使用的函数参数一样,参数列表用逗号分隔。那么参数是按值传递还是按引用传递呢?答案是值传递。如何按引用传递呢?其实和c++里一样,在参数前使用&符号。
那么如何设置缺省的参数值呢?这个和c++一样,在参数列表里直接写上就行了。例如:
php
function makecomputerbrand( $brand = ibm )
{
return making . $brand . computer now.
;
}
echo makecomputerbrand();
echo makecomputerbrand( dell );
echo makecomputerbrand( hp );
echo makecomputerbrand( lenevo );
?>
输出的结果是:
making ibm computer now .
making dell computer now .
making hp computer now .
making lenevo computer now .
3. 函数是否支持重载?
不支持。
4 .函数的返回值是如何定义的。
如果单独返回一个值或不返回值,和普通语言一样,return就可以。但是若返回多个值,一种方法是返回一个数组。例如:
php
function small_numbers()
{
return array ( 0 , 1 , 2 );
}
list ( $zero , $one , $two ) = small_numbers();
?>
5. 函数有变量函数吗?
有,和可变变量一样。