php.function.特殊形式的函数

嵌套函数

1
2
3
4
5
6
7
function out(){
function in(){
echo 'in...';
}
}
out(); // in函数自动全局注册
in() // in...

递归函数

1
2
3
4
5
6
7
8
9
10
11
function test($i) {
echo "$i ";
sleep(1);
if ($i > 0) {
$fn = __FUNCTION__;
$fn($i - 1);
}
echo "$i ";
};

test(3); // 3 2 1 0 0 1 2 3

魔术常量 __FUNCTION__ 在函数体内返回该函数被定义时的名字

递归示意图

递归示意图

匿名函数

1
2
3
4
5
$fn = function ($msg) {
echo $msg;
}

$fn('hello');

使用create_function创建匿名函数

1
2
$fn = craete_function('$msg, $name', 'echo "$msg, $name."');
$fn('hello', 'tom'); // hello, tom.

回调中

1
2
3
$arr = [1,2,3,4,5,6];
$arr = array_map(function($value){ return $value * 2; }, $arr);
print_r($arr);
1
call_user_func(function($username){ echo "hello, $username";}, 'tom');	// hello,tom

可变函数

1
2
$fn = 'md5';
$fn('123456'); // 等价于 md5('123456')

不能用于 echo print unset isset empty include require 等语言结构,需要自己封装后使用

1
2
3
4
5
6
function say($msg) {
echo $msg;
}

$fn = 'say';
$fn('hello world!');

回调函数

1
2
3
4
5
6
7
8
function say(){ echo 'saying...'; }
function run(){ echo 'running...'; }

funtion doWhat($cb) {
$cb();
}
doWhat('say');
doWhat('run');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function handle($data){
var_dump($data);
}

function register($data, $cb) {
$cb($data);
}

$data = [
'name' => 'tom',
'sex' => 'male',
'age' => 20
];

register($data, 'handle');

array_map array_walk array_filter

1
2
$arr = ['tom', 'jack'];
array_map('strtoupper', $arr);
1
2
3
$arr = ['tom', 'jack'];
function prefix(&$value, $key, $prefixStr) { $value = "{$prefixStr}: {$value}";}
array_walk($arr, 'prefix', 'name');
1
2
3
4
5
6
7
8
9
10
11
function odd($var)
{
// returns whether the input integer is odd
return($var & 1); // 按位与 奇数返回 0,偶数返回1
}

$arr = [1,2,3,4,5,6,7,8,9];

$arr = array_filter($arr, 'odd');

print_r($arr);

call_user_func call_user_func_array

可变参数形式的函数

更多 可变参数

1
2
3
4
function test(...$num){
print_r($num);
}
test('hello', 'world');