PHP Closure 类的bind简介和使用
2021/6/13 14:21:56
本文主要是介绍PHP Closure 类的bind简介和使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、Closure 类 的作用
面向对象变成语言代码的复用主要采用继承来实现,而函数的复用,就是通过闭包来实现。这就是闭包的设计初衷。
注:PHP里面闭包函数是为了复用函数而设计的语言特性,如果在闭包函数里面访问指定域的变量,使用use关键字来实现。
2、核心方法 bind 扩展一个类的功能,并能在外边可以使用类内部的私有属性(protected和provide )。看demo
class Student { private $name = "jim"; protected $age = 38; public function say() { } } class Teacher { public $name = "Lucas"; public $age = 4; public function say() { } } //创建需要共用的匿名函数 $closureFunc = function ($name,$age) { $this->name = $name; $this->age = $age; echo get_class($this).":My name is {$this->name}, I'm {$this->age} years old.\n"; }; $student = new Student(); $teacher = new Teacher(); //把$closure中的$this绑定为$person //这样在$bound_closure中设置name和age的时候实际上是设置$person的name和age //也就是绑定了指定的$this对象($person) $bound_teacher = Closure::bind($closureFunc, $teacher);//把对象$bound_teacher 指针绑定给匿名函数 $closureFunc ,让$closureFunc有访问对象属性的能力 $bound_student = Closure::bind($closureFunc, $student,"Student");//如果对象的属性是protected 或 private 还需要传第三参数:类名 “Student” $bound_student('amy',37);//输出 Student:My name is amy, I'm 37 years old. $bound_teacher('liangshaoxi',74);//输出 Teacher:My name is liangshaoxi, I'm 74 years old. echo '$teacher->name:'.$teacher->name.PHP_EOL;//输出 $teacher->name:liangshaoxi ,已经把对象$student 的私有属性name改为liangshaoxi
这篇关于PHP Closure 类的bind简介和使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28怎么把PHP程序打包?-icode9专业技术文章分享
- 2024-09-28怎么用Phar打包PHP程序?-icode9专业技术文章分享
- 2024-09-13手动在github上下载的mfpt包,怎么放到thinkphp5.0框架并正常使用-icode9专业技术文章分享
- 2024-09-05python的<class 'bytearray'>相当于php的哪个数据类型-icode9专业技术文章分享
- 2024-09-05php 导出银行卡号避免科学技术法的方法-icode9专业技术文章分享
- 2024-08-30什么样的php代码质量差被称为垃圾代码-icode9专业技术文章分享
- 2024-08-30用 PHP 调用拼多多的接口以获取订单状态消息的步骤方法和代码示例-icode9专业技术文章分享
- 2024-08-27phpunit单元测试框架的入门和使用方法介绍-icode9专业技术文章分享
- 2024-08-24PHP 中date("w") 周一是多少-icode9专业技术文章分享
- 2024-08-14thinkphp8.0获取域名或主机名方法-icode9专业技术文章分享