温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP如何实现中后期延迟静态绑定

发布时间:2021-03-03 17:07:54 来源:亿速云 阅读:129 作者:TREX 栏目:开发技术

这篇文章主要介绍“PHP如何实现中后期延迟静态绑定”,在日常操作中,相信很多人在PHP如何实现中后期延迟静态绑定问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”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如何实现中后期延迟静态绑定”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI