zoukankan      html  css  js  c++  java
  • PHP 闭包函数

    PHP>v5.3闭包函数,闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函数来处理

    匿名函数也叫闭包函数(closures允许创建一个没有指定没成的函数,最经常用作回调函数参数的值。

    闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函数来处理。

    闭包内部函数使用了外部函数中定义的变量.在PHP新开放的闭包语法中, 我们就是用use来使用闭包外部定义的变量的。

    正常函数:

      function  cl($name){
           return sprintf('hello %s',$name);
      }

    打印:

    echo cl('world');

    结果:hello world

    匿名函数:

      $cl = function($name){
        return sprintf('hello %s',$name);
      };
      echo $cl('world');

    结果:hello world

    打印$cl 类型

    object(Closure)#1 (1) {
      ["parameter"]=>
      array(1) {
        ["$name"]=>
        string(10) ""
      }
    }

    直接通过定义为匿名函数的变量名称来调用

    echo preg_replace_callback('~-([a-z])~', function ($match) {
      return strtoupper($match[1]);
    }, 'hello-world');

    结果:helloWorld

    使用use

    $message = 'hello';
    $example = function() use ($message){
      var_dump($message);
    };
    echo $example();

    结果:string(5) "hello"

    带参数:

    $message = 'hello';
    $example = function ($data) use ($message){
      return "{$data},{$message}";
    };
    
    echo $example('world');

    结果:world,hello

    闭包不会改变外部变量

    $message = 'hello';
    $test = function () use ($message){
     var_dump($message);
     $message = 'Hi……';
    };
    $test();   
    
    $message = 'Ni Hao!';
    $test(); 

    结果:

    string(5) "hello"
    string(5) "hello"

    转载来自:http://www.phperz.com/article/16/0227/190900.html

  • 相关阅读:
    javascript模拟jQuery封装委托事件,兼容IE
    javascript事件有哪些?javascript的监听事件
    javascript阻止事件冒泡的兼容写法及其相关示例
    Spring的特点
    异常以及为什么要学异常
    Windows下干活儿辅助软件
    Oracle EBS SLA 详解
    EBS获取并发程序Trace File
    EBS Custom Password Rules
    Oracle PLSQL读取(解析)Excel文档
  • 原文地址:https://www.cnblogs.com/dcb3688/p/4608030.html
Copyright © 2011-2022 走看看