php 匿名方法,PHP 匿名函数 - light_的个人空间 - OSCHINA - 中文开源技术交流社区

回调函数(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");

8ead9a38c0047d6b04a9ae82bdaeb7c9.png

匿名函数变量赋值示例

$name = 'ccc';

$test = function(...$t) use($name){

var_dump($t);

var_dump($name);

};

$test(1,2,3);

fdae7e18cbd86d56dc6977474b2799b3.png

Closure bind

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

506d89a38bb11c9f3b91e1c4e51eab62.png

Closure bindTo

$test = new \app\Test();

$cl2 = function (){

$this->test1();

};

$cl3 = $cl2->bindTo($test,\app\Test::class);

$cl3();

c968eb107615ab892c168991bdf5c1a3.png

Closure call

$test = new \app\Test();

$cl2 = function (){

$this->test1();

};

$cl2->call($test); // 注意此方法与bindTo的不同

a277f89fff0fc434ed622eba39807959.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值