函数
# 用户自定义函数
一个函数的结构如下所示
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
2
3
4
5
6
可以给函数设置条件
<?php
$makefoo = true;
/* 不能在此处调用foo()函数,
因为它还不存在,但可以调用bar()函数。*/
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* 现在可以安全调用函数 foo()
因为 $makefoo 值为真 */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.\n";
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
函数之间还可以嵌套
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
/* 现在还不能调用 bar() 函数,因为它还不存在 */
foo();
/* 现在可以调用 bar() 函数了,因为 foo() 函数
的执行使得 bar() 函数变为已定义的函数 */
bar();
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 函数的参数
# 可以设置多个参数,这里我们还可以传递数组
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
2
3
4
5
# 使用引用来传递参数
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
2
3
4
5
6
7
8
# 给参数设置默认值
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
2
3
4
5
6
7
8
输出
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
2
3
# 可变参数
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
2
3
4
5
6
7
8
9
我们也可以这样来传递
<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
2
3
4
5
6
7
# 命名参数
这个是PHP8的内容,先不管
# 可变函数
PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。
一般来说,我们会使用这个作为回调函数
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// 使用 echo 的包装函数
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
也可以对对象进行操作
<?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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
调用对象里面的静态方法
<?php
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}
echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope.
2
3
4
5
6
7
8
9
10
11
12
一些更加复杂的用法
<?php
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}
$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar"
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 内置函数
PHP 有很多标准的函数和结构。还有一些函数需要和特定地 PHP 扩展模块一起编译,否则在使用它们的时候就会得到一个致命的“未定义函数”错误。例如,要使用 image (opens new window) 函数中的 imagecreatetruecolor() (opens new window),需要在编译 PHP 的时候加上 GD 的支持。或者,要使用 mysqli_connect() (opens new window) 函数,就需要在编译 PHP 的时候加上 MySQLi (opens new window) 支持。有很多核心函数已包含在每个版本的 PHP 中如字符串 (opens new window)和变量 (opens new window)函数。调用 phpinfo() (opens new window) 或者 get_loaded_extensions() (opens new window) 可以得知 PHP 加载了那些扩展库。同时还应该注意,很多扩展库默认就是有效的。PHP 手册按照不同的扩展库组织了它们的文档。请参阅配置 (opens new window),安装 (opens new window)以及各自的扩展库章节以获取有关如何设置 PHP 的信息。
# 匿名函数
匿名函数(Anonymous functions),也叫闭包函数(closures
),允许 临时创建一个没有指定名称的函数。最经常用作回调函数 callable (opens new window)参数的值。当然,也有其它应用的情况。
匿名函数目前是通过 Closure (opens new window) 类来实现的。
比如下面这个,我们进行正则表达式匹配,然后第二个参数我们可以传递一个函数进去
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
2
3
4
我们可以直接把函数赋值给变量
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
2
3
4
5
6
7
一些更加常用的方法
<?php
$message = 'hello';
// 没有 "use",这里会报错。。。
$example = function () {
var_dump($message);
};
// 输出NULL
$example();
// 继承 $message,这里我们可获取到$message的内容
$example = function () use ($message) {
var_dump($message);
};
// 输出string(5) "hello"
$example();
// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
//输出string(5) "hello"
$example();
// Reset message
$message = 'hello';
// Inherit by-reference
$example = function () use (&$message) {
var_dump($message);
};
// 输出string(5) "hello"
$example();
// 这里使用的引用数据,所以我们这里会输出新的值
$message = 'world';
// 输出string(5) "world"
$example();
// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
// 输出string(11) "hello world"
$example("hello");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 静态匿名函数
匿名函数允许被定义为静态化。这样可以防止当前类自动绑定到它们身上,对象在运行时也可能不会被绑定到它们上面,下面这个代码会报错
<?php
class Foo
{
function __construct()
{
$func = static function() {
var_dump($this);
};
$func();
}
};
new Foo();
2
3
4
5
6
7
8
9
10
11
12
# 箭头函数
箭头函数是 PHP 7.4 的新语法,是一种更简洁的 匿名函数 (opens new window) 写法。
匿名函数和箭头函数都是 Closure (opens new window) 类的实现,下面是一个最简单的箭头函数的用法
<?php
$y = 1;
$fn1 = fn($x) => $x + $y;
// 相当于 using $y by value:
$fn2 = function ($x) use ($y) {
return $x + $y;
};
var_export($fn1(3));
2
3
4
5
6
7
8
箭头函数可以自动捕捉变量的值,即使在嵌套的情况下
<?php
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
// 输出 51
var_export($fn(5)(10));
2
3
4
5
箭头函数不能修改外部变量的值
<?php
$x = 1;
$fn = fn() => $x++; // 不会影响 x 的值
$fn();
var_export($x); // 输出 1
2
3
4
5