PHP 匿名函数

博客主要介绍了PHP和Python中的回调函数与匿名函数(闭包函数),还给出了匿名函数示例、匿名函数变量赋值示例,以及Closure相关的bind、bindTo、call等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

回调函数(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的不同

转载于:https://my.oschina.net/u/925519/blog/3045969

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值