如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
常见的函数类型
引用函数
和引用变量类似,共用一个变量
1 2 3 4 5 6 7 8 9 10 11 |
$b = 10; $b = &$a; function test(&$a) { $a = 30; echo $a; } test($b); echo $b;//30 |
变量函数
1 2 3 4 |
$a = 'abs';//函数 echo abs(-100);//100 |
回调函数
将一个函数名作为一个参数,被作为函数传递的函数名就是回调函数,其实就是在函数内部使用变量函数
1 2 3 4 5 6 7 8 9 10 11 |
function sum($a,$b) { echo $a+$b; } function rel($a,$b,$fs='') { return $fs($a,$b);//调用函数 } $c = rel(10,20,'sum'); echo $c; |
递归函数
- 自己调用自己
- if不会终止程序,如果判断完成继续执行后面的代码,如果想要结束用die
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function sum1($a) { if($a>0){ return $a+sum1($a-1); } if($a==0){ return $a=0; } if($a<0){ return "请输入一个正数"; } } $a = sum1(5); echo "<br/>"; echo $a;//15 echo "<br/>"; $a = sum1(0); echo "<br/>"; echo $a;//0 |
匿名函数
- 没有函数名,赋值给一个变量,使用时直接变量()
1 2 3 4 5 6 |
$a = function($b) { echo $b; }; echo $a(5) |
- 匿名函数要想使用外部变量时可以使用全局变量或use(&$a,&$b)
1 2 3 4 5 6 7 8 |
$c = 10; $a =function ($b) use(&$c) { return $b+$c; }; echo $a(5); |
函数的引用
- require
- include
- require_once
- include_once
共同点:
都可以将php文件引入另一个php文件中
不同点:
1. require与include
– require引用失败会报error级别的错误,后面脚本停止运行
– include引用失败会报warning级别错误,继续运行后面脚本
- require_once与include_once
- require_once引用失败会报error级别的错误,后面脚本停止运行
- include_once引用失败会报warning级别错误,继续运行后面脚本
- require/include与include.include_once
- 使用include_once的使用的时候先检查此文件是否已经被导入,如果被导入了,就不会再次重复导入