Closure class用来表示匿名函数 (anonymous function), PHP 5.3 开始支持,
<?php
/*
class Closure {
private __construct()
public static bind(Closure $closure, ?object $newThis, object|string|null $newScope = 'static'): ?Closure
public bindTo(object $newthis, object|string|null $newScope = 'static'): ?Closure
}
bind: 复制一个 closure 绑定指定的 $this 和类作用域, 第一个参数是需要绑定的匿名函数, 第二个参数是要指定的 $this, 第三个参数是想要绑定给 closure 的类作用域, 'static' 表示不改变, 如果传入一个物件则使用这物件的类型名, 类作用域用来决定 closure 中 $this 物件的属性可见性
bindTo: 复制当前 closure 绑定指定的 $this 和类作用域
*/
class A{
private static $_cat = 'cat';
private $_dog = 'dog';
public $pig = 'pig';
}
$cat = function() {
echo A::$_cat;
};
$dog = function() {
echo $this->_dog;
};
$pig = function() {
echo $this->pig;
};
$bindCat = Closure::bind($cat, null, 'A');
$bindDog = Closure::bind($dog, new A(), 'A');
$bindPig = Closure::bind($pig, new A());
$bindCat();
echo "\n";
$bindDog();
echo "\n";
$bindPig();
echo "\n";
匿名函数
<?php
// 匿名函数, 定义一个函数体, 将函数体赋值给一个变数
$func = function() {
echo "this is a function\n";
};
$func1 = function($param) {
var_dump($param);
};
// 将匿名函数作为参数传入
function dFunc($func, $param) {
$func($param);
}
dFunc($func1, '123');
// 定义一个函数, 在该函数中将内部的匿名函数返回
function cFunc($param) {
$func = function($param1) use ($param) {
echo "param:".$param1." ".$param;
};
return $func;
}
$rFunc = cFunc("123");
$rFunc("456");
区域变数(local variable)
在 function 中宣告, 可视范围在 function 内, 不需使用任何关键字, 函数执行结束後就消失
全域变数(global variable)
在 function 外宣告, 整个档案可视, 但在 function 内使用要使用 global 关键字, 注明使用 global 变数
<?php
$a = 1;
$b = 2;
include 'b.inc'; // $a 也会在 b.inc 里可用
function Test() {
global $a; // 使用 global 变数 $a
echo $a;
}
Test();
// 或使用超全域(superglobal)变数 $GLOBALS, 一个包含全部变数的的全域组合阵列, 变数名就是 key
function Test2() {
echo $GLOBALS['b'];
}
Test2();
静态变数(static variable)
只存在於函数中, 但函数执行结束後不会消失
<?php
function test() {
static $a = 0;
echo $a;
$a++;
}
test();
test();
转换操作符 map/mapError map操作符会执行给定的闭包,将上游发布的内容进行转换,然後再...
这礼拜在弄第九周作业,在 session 的部分花相对多的时间研究,主要是安全议题的关系。 然後也开...
PyAutoGUI 一个可以用来控制键盘和滑鼠的套件 键盘控制 press(key) 按下再放开某键...
昨天简单介绍了网路服务的C/S与B/S的差别,今天简单介绍browser-server model的...
您的Seagate希捷外接式硬碟机无响应/希捷外接式硬碟机无法读取/Seagate外接式硬碟机没有回...