php.sprintf

格式值

字符串 s

1
2
3

$format = "%s";
echo sprintf($format, 'hello'); // hello

十进制数字 d

1
2
3

$format = "%d";
echo sprintf($format, 2); // 2

浮点数 f / F

1
2
$format = "%f";
echo sprintf($format, 2); // 2.000000
  • f 本地设置
  • F 非本地设置

附加格式值

必须放在%与格式值字母之间,例如 %.2f

在正数前面加上 + 标记

1
2
3
4
5
6
7
$format = '%+d';
echo sprintf($format, 2); // +2
echo sprintf($format, -2); // -2

$format = '%d';
echo sprintf($format, 2); // 2
echo sprintf($format, -2); // -2

小于最小宽度时填充 ‘x

'x 单个单引号开头,’x’可以是任意单个字符
必须和宽度指示器一起使用。

1
2
3
4
5
$format = "%'x5s";  // 当宽度小于5时用x填充为5位
echo sprintf($format, 'a'); // 'xxxxa'

$format = "%'03d";
echo sprintf($format, 2); // '002' 最小宽度为3,小于3位时,用0补位

后置填充

1
2
3
4
5
$format = "%'x5d";  // 默认前置填充
echo sprintf($format, 2); // xxxx2

$format = "%'x-5d"; // 后置填充
echo sprintf($format, 2); // 2xxxx

宽度指示器 [0-9]

规定变量值的最小宽度,宽度不够时,用空格补位

1
2
$format = '%3d';
echo sprintf($format, 2); // ' 2';

小数位数或最大字符串长度 .[0-9]

1
2
3
4
5
$format = '%.2f';
echo sprintf($format, 3);

$format = '%.2s';
echo sprintf($format, '123456'); // '12' 最大宽度为2,从左向右取两位

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');