久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

PHP延遲靜態綁定使用方法實例解析

瀏覽:102日期:2022-09-09 09:00:30

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
相關文章:
主站蜘蛛池模板: 招远市| 喜德县| 禹城市| 黎城县| 通榆县| 郁南县| 商洛市| 宁陕县| 乌苏市| 元氏县| 巫溪县| 平遥县| 南充市| 彭水| 富源县| 山丹县| 沁阳市| 奎屯市| 安陆市| 镇远县| 北安市| 浦北县| 班戈县| 恩施市| 重庆市| 同仁县| 阿鲁科尔沁旗| 炎陵县| 松阳县| 霍城县| 梁山县| 揭西县| 双桥区| 孟州市| 闻喜县| 聂拉木县| 元谋县| 华宁县| 石景山区| 桓台县| 英德市|