PHP性状闭包,PHP 闭包

一、概述

闭包是指在创建时封装周围状态的函数,即使闭包所在的环境的不存在了,闭包中封装的状态依然存在。

闭包对象实现了__invoke()魔术方法,只要变量名后有(),PHP就会查找并调用__invoke方法。

1、闭包可以赋值给变量

2、闭包可以作为参数(回调函数)传递给函数

3、闭包可以作为函数的返回值

4、定义一个闭包函数,即产生了一个闭包类(Closure)的对象

Closure {

/* 方法 */

__construct ( void )

public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )

public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] )

}

方法说明:

Closure::bind: 复制一个闭包,绑定指定的 $this 对象和类作用域。是 Closure::bindTo() 的静态版本。

Closure::bindTo: 复制当前闭包对象,绑定指定的 $this 对象和类作用域。

bind参数和返回值说明:

closure:表示需要绑定的闭包对象。

newthis:表示需要绑定到闭包对象的对象,或者 NULL 创建未绑定的闭包。

newscope:表示想要绑定给闭包的类作用域,可以传入类名或类的示例,默认值是'static', 表示不改变。

该方法成功时返回一个新的 Closure 对象,失败时返回 FALSE。

bindTo参数和返回值说明:

newthis:表示需要绑定到闭包对象的对象,或者 NULL 创建未绑定的闭包。

newscope:表示想要绑定给闭包的类作用域,可以传入类名或类的示例,默认值是'static', 表示不改变。

class Animal {

private static $cat = "cat";

private $dog = "dog";

public $pig = "pig";

public function say(string $param)

{

return 'hello '. $param;

}

}

/*

* 获取Animal类静态私有成员属性

*/

$cat = static function() {

return Animal::$cat;

};

/*

* 获取Animal实例私有成员属性

*/

$dog = function() {

return $this->dog;

};

/*

* 获取Animal实例公有成员属性

*/

$pig = function() {

return $this->say($this->pig);

};

// 给闭包绑定了Animal实例的作用域,但未给闭包绑定$this对象,因此不能使用$this对象

$bindCat = Closure::bind($cat, null, new Animal());

// 给闭包绑定了Animal类的作用域,同时将Animal实例对象作为$this对象绑定给闭包,因此可以访问非公有的属性和方法

$bindDog = Closure::bind($dog, new Animal(), 'Animal');

// 将Animal实例对象作为$this对象绑定给闭包,保留闭包原有作用域,因此只能调用公有的属性和方法

$bindPig = Closure::bind($pig, new Animal());

// 根据绑定规则,允许闭包通过作用域限定操作符获取Animal类静态私有成员属性,若没有作用域,则只能访问公有的

echo $bindCat(),'
'; // cat

// 根据绑定规则,允许闭包通过绑定的$this对象(Animal实例对象)获取Animal实例所有的成员属性和方法

echo $bindDog(),'
'; // dog

// 根据绑定规则,允许闭包通过绑定的$this对象获取Animal实例公有成员属性和方法

echo $bindPig(),'
'; // hello pig

// bindTo与bind类似,bind是bindTo的静态版本,这里只举一个,其他类比就可以

$bindCat = $cat->bindTo(null, 'Animal');

echo $bindCat(); // cat

class A {

function __construct($val) {

$this->val = $val;

}

function getClosure() {

//returns closure bound to this object and scope

return function() { return $this->val; };

}

}

$ob1 = new A(1);

$ob2 = new A(2);

$cl = $ob1->getClosure();

echo $cl(), "\n"; // 1

$cl = $cl->bindTo($ob2);

echo $cl(), "\n"; // 2

标签:闭包,Closure,对象,绑定,作用域,Animal,PHP

来源: https://www.cnblogs.com/cshaptx4869/p/10775068.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值