新聞中心
創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)php中self關(guān)鍵字的使用方法,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
用法:
self總是指向“當(dāng)前類(及類實(shí)例)”。
詳細(xì)介紹:
1、替代類名,引用當(dāng)前類的靜態(tài)成員變量和靜態(tài)函數(shù);
2、抑制多態(tài)行為,引用當(dāng)前類的函數(shù)而非子類中覆蓋的實(shí)現(xiàn);
下面我們通過實(shí)例來與 parent 、 static 以及 this進(jìn)行對(duì)比。
parent
self 與 parent 的區(qū)分比較容易: parent 引用父類/基類被隱蓋的方法(或變量), self則引用自身方法(或變量)。例如構(gòu)造函數(shù)中調(diào)用父類構(gòu)造函數(shù):
class Base { public function __construct() { echo "Base contructor!", PHP_EOL; } } class Child { public function __construct() { parent::__construct(); echo "Child contructor!", PHP_EOL; } } new Child; // 輸出: // Base contructor! // Child contructor!
static
static 常規(guī)用途是修飾函數(shù)或變量使其成為類函數(shù)和類變量,也可以修飾函數(shù)內(nèi)變量延長其生命周期至整個(gè)應(yīng)用程序的生命周期。但是其與 self 關(guān)聯(lián)上是PHP 5.3以來引入的新用途:靜態(tài)延遲綁定。
有了 static 的靜態(tài)延遲綁定功能,可以在運(yùn)行時(shí)動(dòng)態(tài)確定歸屬的類。例如:
class Base { public function __construct() { echo "Base constructor!", PHP_EOL; } public static function getSelf() { return new self(); } public static function getInstance() { return new static(); } public function selfFoo() { return self::foo(); } public function staticFoo() { return static::foo(); } public function thisFoo() { return $this->foo(); } public function foo() { echo "Base Foo!", PHP_EOL; } } class Child extends Base { public function __construct() { echo "Child constructor!", PHP_EOL; } public function foo() { echo "Child Foo!", PHP_EOL; } } $base = Child::getSelf(); $child = Child::getInstance(); $child->selfFoo(); $child->staticFoo(); $child->thisFoo();
程序輸出結(jié)果如下:
在函數(shù)引用上, self 與 static 的區(qū)別是:對(duì)于靜態(tài)成員函數(shù), self 指向代碼當(dāng)前類, static 指向調(diào)用類;對(duì)于非靜態(tài)成員函數(shù), self 抑制多態(tài),指向當(dāng)前類的成員函數(shù), static 等同于 this ,動(dòng)態(tài)指向調(diào)用類的函數(shù)。
上述就是小編為大家分享的php中self關(guān)鍵字的使用方法了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道。
本文題目:php中self關(guān)鍵字的使用方法-創(chuàng)新互聯(lián)
分享地址:http://www.ef60e0e.cn/article/esgis.html