PHP延遲靜態(tài)綁定使用方法實(shí)例解析
PHP的繼承模型中有一個(gè)存在已久的問(wèn)題,那就是在父類中引用擴(kuò)展類的最終狀態(tài)比較困難。我們來(lái)看一下代碼清單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
在這個(gè)例子中,render()方法中使用了self關(guān)鍵字,這是指ParentBase類而不是指Descendant類。在ParentBase::render()方法中沒(méi)法訪問(wèn)$property的最終值。為了解決這個(gè)問(wèn)題,需要在子類中重寫(xiě)render()方法。
通過(guò)引入延遲靜態(tài)綁定功能,可以使用static作用域關(guān)鍵字訪問(wèn)類的屬性或者方法的最終值,如代碼所示。
<?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
通過(guò)使用靜態(tài)作用域,可以強(qiáng)制PHP在最終的類中查找所有屬性的值。除了這個(gè)延遲綁定行為,PHP還添加了get_called_class()函數(shù),這允許檢查繼承的方法是從哪個(gè)派生類調(diào)用的。以下代碼顯示了使用get_called_class()函數(shù)獲得當(dāng)前的類調(diào)用場(chǎng)景的方法。
使用get_called_class()方法
<?php class ParentBase { public static function render() { return get_called_class(); } } class Decendant extends ParentBase {} echo Descendant::render(); Descendant
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5動(dòng)態(tài)(可拖動(dòng)控件大小)布局控件QSplitter詳細(xì)使用方法與實(shí)例2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. js開(kāi)發(fā)中的頁(yè)面、屏幕、瀏覽器的位置原理(高度寬度)說(shuō)明講解(附圖)4. CSS清除浮動(dòng)方法匯總5. 不要在HTML中濫用div6. XML入門(mén)的常見(jiàn)問(wèn)題(三)7. Python數(shù)據(jù)分析JupyterNotebook3魔法命令詳解及示例8. ASP動(dòng)態(tài)include文件9. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫(xiě)金額)的函數(shù)10. vue跳轉(zhuǎn)頁(yè)面常用的幾種方法匯總
