您現在所在位置: 主頁(yè) > 網(wǎng)站優(yōu)化
PHP延遲靜態(tài)綁定使用方法實(shí)例解析
更新時(shí)間:2026-05-05 00:12:02
這篇文章主要介紹了PHP延遲靜態(tài)綁定使用方法實(shí)例解析,延用方文中通過(guò)示例代碼介紹的非常(′▽?zhuān)?)詳細,對大家的遲靜學(xué)習或者工作具有一定的參考學(xué)習價(jià)值,需要的朋友可以參考下
PHP的繼承模型中??有一個(gè)存在已久的問(wèn)題,那就(′▽?zhuān)?是態(tài)綁在父類(lèi)中引用??擴展類(lèi)的最終狀態(tài)比較困難。我們來(lái)看一下代碼清單5-11中的定使例子。
代碼清ヽ(′?`)ノ單5-11 意想不到的法實(shí)繼承
<?php
class ParentBase {
static $property = 'Par??ent Value';
public static fun(′?`*)ction render((◎_◎;)) {
return self::$property;
}
}
class Descendant extends ParentBase {
stat??ic $property = 'Descendant Value';
}
echo Descendant::render();
Parent Valu??e
在這個(gè)例子中,render()方法中使用了self關(guān)鍵字,例解這是延用方指ParentBase類(lèi)而不是指Descendant類(lèi)。在ParentBase::render()方法中沒(méi)法訪(fǎng)問(wèn)$property的遲靜最終值。為了解決這個(gè)問(wèn)題,態(tài)綁需要在子類(lèi)中重寫(xiě)render()方法。定使
通過(guò)引入延遲靜態(tài)綁定功能,法實(shí)(′_`)可以使用static作用域關(guān)鍵字訪(fǎng)問(wèn)類(lèi)的例解屬性或者方法的最終值,如代碼所示。延用方
<?遲靜php
clas??s ParentBase {
static $property = 'Parent Value';
public static function rende(╯°□°)╯︵ ┻━┻r() {
return static::$property;
}
}
class Desce(′?ω?`)ndant extends ParentBase {
static $property = 'Descendant Val??ue';
}
echo Descen??dant::render();
Descendant Value
通過(guò)使用靜態(tài)作用域,可以強制PHP在最終的態(tài)綁類(lèi)中查找所有屬性的值。除了這個(gè)延遲綁定行為,PHP還添加了get_called_class??()函數,這允許檢查繼承的方法是從哪個(gè)派生類(lèi)調用的。以下代碼顯示了使用get_called_class()函數獲得當前的類(lèi)調(diao)用場(chǎng)景的方法。
使用get_called_class()方法
<?php
class ParentBase {
public sta?tic function render() {
return get_called_class();
}
}
class Decendant extends ParentBase { }
echo Descendant::render( ?° ?? ?°)();
Descendant
來(lái)源:腳本之家
鏈接:https://www.jb51.net/article/194985.htm

