PHP closure Functions For example, you can use this now:
| The code is as follows |
Copy Code |
|
$closure = function ($param) {echo $param;}; |
Feel and JS is not the same usage.
Some examples of closed-pack functions
| The code is as follows |
Copy Code |
|
function Test () {
$test = ';
$test =function ($STR) {
echo ' Test ';
return $str;
};
Timeout (' y-m-d h:i:s ', function ($time) {
$this->date=time ();
return $time -24*60*60;
});
Var_dump ($test (' Hello word! '));
}
function timeout ($format, $time) {
echo Date ($format, $time (Time ()));
}
Test ();
?> |
Previous example output
2013-11-19 16:24:56teststring (one) "Hello word!"
You can use a function with this argument.
The condition is that php3.0 after PHP 4.0 the closure function supports $this usage
Closure functions are commonly used in Preg_match and other callback functions.
| The code is as follows |
Copy Code |
|
Class A {
private static $sfoo = 1;
Private $ifoo = 2;
}
$CL 1 = static function () {
Return A:: $sfoo;
};
$CL 2 = function () {
return $this->ifoo;
};
$BCL 1 = closure::bind ($CL 1, NULL, ' A ');
$BCL 2 = Closure::bind ($cl 2, new A (), ' a ');
echo $BCL 1 (), "n";
echo $BCL 2 (), "n";
?> |
Output
1
2
Bind class can be used in a closed package function
| The code is as follows |
Copy Code |
|
Class A1 {
function __construct ($val) {
$this->val = $val;
}
function Getclosure () {
Returns closure bound to this object and scope
return function () {return $this->val;};
}
}
$ob 1 = new A1 (1);
$ob 2 = new A1 (2);
$CL = $ob 1->getclosure ();
Echo $cl (), "n";
$CL = $cl->bindto ($ob 2);
Echo $cl (), "n";
?> |
The output of the above routine is similar to the following:
1
2
BindTo can bind classes again in a class
| The code is as follows |
Copy Code |
|
$FN = function () {
return + + $this->foo; Increase the value
};
Class bar{
Private $foo = 1; Initial value
}
$bar = new Bar ();
$FN 1 = $fn->bindto ($bar, ' Bar '); Specify Class name
$FN 2 = $fn->bindto ($bar, $bar); or object
$FN 3 = $fn 2->bindto ($bar); or object
echo $FN 1 (); 2
echo $FN 2 (); 3
echo $FN 3 (); 4
?> |
A binding class is required outside the class to be used, and the binding can be a class name or an object, and can be bound again without the need for an arch class name or object