回調函數(callback)
PHP是將函數以string形式傳遞的.
function testCallBack()
{
echo "test function.\n";
}
class Test
{
public function testCallBack()
{
echo "test class \n";
}
}
call_user_func("testCallBack");//調用一個函數
$test = new \Test();
call_user_func(array($test,"testCallBack"));//調用一個對象的方法
匿名函數(Closure[閉包函數])
- 匿名函數示例
call_user_func(function(...$t){
var_dump($t);
},"ccc","sss");
![](http://static.javashuo.com/static/loading.gif)
- 匿名函數變量賦值示例
$name = 'ccc';
$test = function(...$t) use($name){
var_dump($t);
var_dump($name);
};
$test(1,2,3);
![](http://static.javashuo.com/static/loading.gif)
- Closure bind
// Test.php
<?php
namespace app;
class Test
{
public function test()
{
echo "test\n";
}
private function test1()
{
echo "test1\n";
}
protected function test2()
{
echo "test2\n";
}
}
$test = new \app\Test();
$cl = \Closure::bind(function(){
$this->test();
$this->test1();
$this->test2();
},$test,\app\Test::class);
$cl();
![](http://static.javashuo.com/static/loading.gif)
- Closure bindTo
$test = new \app\Test();
$cl2 = function (){
$this->test1();
};
$cl3 = $cl2->bindTo($test,\app\Test::class);
$cl3();
![](http://static.javashuo.com/static/loading.gif)
- Closure call
$test = new \app\Test();
$cl2 = function (){
$this->test1();
};
$cl2->call($test); // 注意此方法與bindTo的不一樣
![](http://static.javashuo.com/static/loading.gif)