PHP延迟静态绑定使用方法实例解析
作者:tonySuen 时间:2024-06-05 15:41:45
PHP的继承模型中有一个存在已久的问题,那就是在父类中引用扩展类的最终状态比较困难。我们来看一下代码清单5-11中的例子。
代码清单5-11意想不到的继承
<?php
class ParentBase {
static $property = 'Parent Value';
public static function render() {
return self::$property;
}
}
class Descendant extends ParentBase {
static $property = 'Descendant Value';
}
echo Descendant::render();
Parent Value
在这个例子中,render()方法中使用了self关键字,这是指ParentBase类而不是指Descendant类。在ParentBase::render()方法中没法访问$property的最终值。为了解决这个问题,需要在子类中重写render()方法。
通过引入延迟静态绑定功能,可以使用static作用域关键字访问类的属性或者方法的最终值,如代码所示。
<?php
class ParentBase {
static $property = 'Parent Value';
public static function render() {
return static::$property;
}
}
class Descendant extends ParentBase {
static $property = 'Descendant Value';
}
echo Descendant::render();
Descendant Value
通过使用静态作用域,可以强制PHP在最终的类中查找所有属性的值。除了这个延迟绑定行为,PHP还添加了get_called_class()函数,这允许检查继承的方法是从哪个派生类调用的。以下代码显示了使用get_called_class()函数获得当前的类调用场景的方法。
使用get_called_class()方法
<?php
class ParentBase {
public static function render() {
return get_called_class();
}
}
class Decendant extends ParentBase {}
echo Descendant::render();
Descendant
来源:https://www.cnblogs.com/tonysuen/articles/1621091.html
标签:php,延迟,静态,绑定
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python openpyxl读取单元格字体颜色过程解析
2023-02-09 06:57:02
javascript创建数组的最简代码
2013-09-01 21:43:04
解决Pycharm无法import自己安装的第三方module问题
2023-09-02 20:25:53
![](https://img.aspxhome.com/file/2023/5/89325_0s.jpg)
微信小程序wx.request拦截 器使用详解
2023-07-22 09:11:55
Python短信轰炸的代码
2022-11-03 17:35:04
JavaScript队列的应用实例详解【经典数据结构】
2024-04-16 09:53:13
python自动查询12306余票并发送邮箱提醒脚本
2023-08-26 09:34:37
![](https://img.aspxhome.com/file/2023/6/75166_0s.jpg)
Python队列、进程间通信、线程案例
2021-10-23 16:43:03
如何使用Go语言实现远程执行命令
2024-04-25 15:16:39
关于vue.js中实现方法内某些代码延时执行
2024-05-21 10:30:46
MySQL 数据库语句优化的原则
2010-01-20 10:11:00
PHP安全的URL字符串base64编码和解码
2023-09-06 22:04:45
Django模型验证器介绍与源码分析
2023-10-19 13:49:53
![](https://img.aspxhome.com/file/2023/5/76115_0s.png)
Python 在局部变量域中执行代码
2023-06-12 04:57:15
PHP的mysqli_thread_id()函数讲解
2023-06-13 10:09:43
![](https://img.aspxhome.com/file/2023/3/55453_0s.png)
python区块链简易版交易实现示例
2023-09-28 15:20:10
![](https://img.aspxhome.com/file/2023/0/107280_0s.png)
Oracle连续相同数据的统计
2024-01-24 11:23:56
![](https://img.aspxhome.com/file/2023/8/64858_0s.png)
python使用MQTT给硬件传输图片的实现方法
2022-02-09 21:55:59
![](https://img.aspxhome.com/file/2023/2/78672_0s.jpg)
php抓取页面的几种方法详解
2023-11-14 10:53:42
asp检测服务器XmlHttp组件支持情况
2008-03-03 12:30:00