网站首页 > 主流语言 > PHP 正文
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开源网。
- 上一篇: PHP获取类私有属性的3种方法
- 下一篇: PHP autoload使用方法及步骤详解
猜你喜欢
- 2021-07-16 php使用Swoole实现毫秒级定时任务的方法
- 2021-07-16 php实现图片压缩处理
- 2021-07-16 PHP获取类私有属性的3种方法
- 2021-07-16 如何利用PHP实现上传图片功能详解
- 2021-07-16 php7连接MySQL实现简易查询程序的方法
- 2021-07-16 php实现记事本案例
- 2021-07-16 Aliyun Linux 编译安装 php7.3 tengine2.3.2 mysql8.0 redis5的过程详解
- 2021-07-16 php使用event扩展的io复用测试的示例
- 2021-07-16 PHP如何通过带尾指针的链表实现'队列'
- 2021-07-16 php redis setnx分布式锁简单原理解析
你 发表评论:
欢迎- 2952℃JS彻底弄懂GMT和UTC时区
- 2824℃JS使用canvas技术模仿echarts柱状图
- 2649℃JS装饰者模式和TypeScript装饰器
- 2574℃JS ES6展开运算符的几个妙用
- 2543℃vue的ssr服务端渲染示例详解
- 2365℃jquery插件实现图片对比
- 2320℃微信小程序视频弹幕位置随机
- 1817℃docker安装redis设置密码并连接的操作
- 0℃未命名
- 开源分类
- 最近发表
-
- (1)python+selenium第一个自动化脚本:实现打开百度首页并搜索selenium
- Discuz!教程之启用HTTPS后解决各处遗留http://网址问题
- 网站如何识别 你是 selenium爬虫?那我们怎么解决(反反爬)
- 旋转拖动验证码解决方案
- python关键词排名_python实现百度关键词排名查询
- Unity3D研究院之通过ipa或apk获取游戏所使用的unity和Xcode版本
- Unity3D研究院编辑器之脚本生成Preset Libraries(十四)
- 手把手教你Charles抓包工具使用
- python开发的程序内存越来越大_遇到个python进程占用内存太多的问题 | 数据,更懂人心...
- Selenium Python3 请求头配置
- 开源网标签
本文暂时没有评论,来添加一个吧(●'◡'●)