本文目錄一覽:
PHP Static延遲靜態綁定用法分析
本文實例講述了PHP
Static延遲靜態綁定用法。分享給大家供大家參考,具體如下:
PHP5.3以後引入了延遲靜態綁定static,它是為了解決什麼問題呢?php的繼承模型中有一個存在已久的問題,那就是在父類中引用擴展類的最終狀態比較困難。來看一個例子。
class
A
{
public
static
function
echoClass(){
echo
__CLASS__;
}
public
static
function
test(){
self::echoClass();
}
}
class
B
extends
A
{
public
static
function
echoClass()
{
echo
__CLASS__;
}
}
B::test();
//輸出A
在PHP5.3中加入了一個新特性:延遲靜態綁定,就是把本來在定義階段固定下來的表達式或變量,改在執行階段才決定,比如當一個子類繼承了父類的靜態表達式的時候,它的值並不能被改變,有時不希望看到這種情況。
下面的例子解決了上面提出的問題:
class
A
{
public
static
function
echoClass(){
echo
__CLASS__;
}
public
static
function
test()
{
static::echoClass();
}
}
class
B
extends
A
{
public
static
function
echoClass(){
echo
__CLASS__;
}
}
B::test();
//輸出B
第8行的static::echoClass();定義了一個靜態延遲綁定方法,直到B調用test的時候才執行原本定義的時候執行的方法。
更多關於PHP相關內容感興趣的讀者可查看本站專題:《php操作office文檔技巧總結(包括word,excel,access,ppt)》、《php日期與時間用法總結》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
php Late static binding 是什麼?
PHP延遲靜態綁定 Late Static Binding
推薦閱讀以下內容:
As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.
More precisely, late static bindings work by storing the class named in the last “non-forwarding call”. In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A “forwarding call” is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.
This feature was named “late static bindings” with an internal perspective in mind. “Late binding” comes from the fact thatstatic:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a “static binding” as it can be used for (but is not limited to) static method calls.
如何理解php中的後期靜態綁定
使用的保留關鍵字:
static
定義:
static:: 不再被解析為定義當前方法所在的類,而是在實際運行時計算的。也可以稱之為“靜態綁定”,因為它可以用於(但不限於)靜態方法的調用。
self與static的區別:
self調用的就是本身代碼片段這個類,而static調用的是從堆內存中提取出來,訪問的是當前實例化的那個類(即static作用於當前調用的類)
示例一(在靜態環境下)
?phpclass A { public static function who() { echo __CLASS__;
} public static function test() { static::who(); // 後期靜態綁定從這裡開始
}
}class B extends A { public static function who() { echo __CLASS__;
}
}
B::test();?輸出結果是”B”
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/189980.html