zoukankan      html  css  js  c++  java
  • 匿名函数

    
    
    class A
    {
        public $base = 100;
        public function __construct()
        {
            echo "a-->construct";
        }
    }
    class B
    {
        private $base = 1000;
        public function __construct()
        {
            echo "b-->construct";
        }
    }
    class C
    {
        private static $base = 10000;
        public function __construct()
        {
            echo "c-->construct";
        }
    }
    $f = function () {
        return $this->base + 3;
    };
    $sf = static function () {
        return self::$base + 3;
    };
    
    //bind(function,object ,newscope ='static') 这个方法是 Closure::bindTo() 的静态版本
    //function Closure 需要绑定的匿名函数。
    //object 需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。
    //newscop 类作用域,用来决定在闭包中 $this 对象的 私有、保护方法 的可见性
    $a = Closure::bind($f, new A);
    print_r($a());
    echo PHP_EOL;
    $b = Closure::bind($f, new B, 'B');
    print_r($b());
    echo PHP_EOL;
    
    //bindTo
    $c = $sf->bindTo(null, 'C');
    print_r($c());
    echo PHP_EOL;
    exit;

    输出结果

      a-->construct103 b-->construct1003 10003

    c中并没有触发构造函数。
    感觉其实跟trait类很像。但是匿名函数的绑定可以绑定,也可以取消绑定。
  • 相关阅读:
    react hooks子给父传值
    npm安装依赖 and 删除依赖
    react 阻止事件冒泡
    http 500状态码
    vue中插槽slot的使用
    怎样在vue项目中使用axios处理接口请求
    GET 与 POST 其实没有什么区别
    LazyMan
    什么是微服务,什么是分布式
    思索 p5.js 的最佳实践
  • 原文地址:https://www.cnblogs.com/buerr/p/8268424.html
Copyright © 2011-2022 走看看