PHP 匿名函数

回调函数(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[闭包函数])

  1. 匿名函数示例
call_user_func(function(...$t){
    var_dump($t);
},"ccc","sss");

  1. 匿名函数变量赋值示例
$name = 'ccc';
$test = function(...$t) use($name){
    var_dump($t);
    var_dump($name);
};
$test(1,2,3);

  1. 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();

  1. Closure bindTo
$test = new \app\Test();
$cl2 = function (){
  $this->test1();
};
$cl3 = $cl2->bindTo($test,\app\Test::class);
$cl3();

  1. Closure call
$test = new \app\Test();
$cl2 = function (){
  $this->test1();
};
$cl2->call($test); // 注意此方法与bindTo的不一样

相关文章
相关标签/搜索