PHP延遲靜態(tài)綁定使用方法實例解析
PHP的繼承模型中有一個存在已久的問題,那就是在父類中引用擴展類的最終狀態(tà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
在這個例子中,render()方法中使用了self關(guān)鍵字,這是指ParentBase類而不是指Descendant類。在ParentBase::render()方法中沒法訪問$property的最終值。為了解決這個問題,需要在子類中重寫render()方法。
通過引入延遲靜態(tài)綁定功能,可以使用static作用域關(guā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
通過使用靜態(tài)作用域,可以強制PHP在最終的類中查找所有屬性的值。除了這個延遲綁定行為,PHP還添加了get_called_class()函數(shù),這允許檢查繼承的方法是從哪個派生類調(diào)用的。以下代碼顯示了使用get_called_class()函數(shù)獲得當(dāng)前的類調(diào)用場景的方法。
使用get_called_class()方法
<?php
class ParentBase {
public static function render() {
return get_called_class();
}
}
class Decendant extends ParentBase {}
echo Descendant::render();
Descendant
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
fleaphp rolesNameField bug解決方法
fleaphp rolesNameField bug解決方法,需要的朋友可以參考下。2011-04-04
關(guān)于PHP自動判斷字符集并轉(zhuǎn)碼的詳解
本篇文章是對PHP自動判斷字符集并轉(zhuǎn)碼進行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
php過濾所有惡意字符(批量過濾post,get敏感數(shù)據(jù))
最近dedecms報漏洞不斷,這里分享下php的過濾函數(shù),大牛飄過吧,給小黑闊們學(xué)習(xí)交流用2014-03-03
PHP跨平臺獲取服務(wù)器IP地址自定義函數(shù)分享
這篇文章主要介紹了PHP跨平臺獲取服務(wù)器IP地址自定義函數(shù)分享,本文函數(shù)會根據(jù)系統(tǒng)類型選擇不同的命令來獲取服務(wù)器的IP地址,需要的朋友可以參考下2014-12-12
php中多維數(shù)組按指定value排序的實現(xiàn)代碼
這篇文章主要介紹了php中多維數(shù)組按指定value排序的實現(xiàn)代碼,可以實現(xiàn)類似數(shù)據(jù)庫排序字段的排序效果,需要的朋友可以參考下2014-08-08
PHP實現(xiàn)數(shù)組和對象的相互轉(zhuǎn)換操作示例
這篇文章主要介紹了PHP實現(xiàn)數(shù)組和對象的相互轉(zhuǎn)換操作,結(jié)合實例形式分析了php使用get_object_vars以數(shù)組形式訪問對象的方法,以及對象與數(shù)組相互轉(zhuǎn)換操作技巧,需要的朋友可以參考下2019-03-03

