php static与self,PHP5.3新特性static与self区别
很多人都說,PHP 簡(jiǎn)單,入門門檻較低,但是要學(xué)精通確很難。隨著 PHP 不斷的發(fā)展,新特性不斷的增加,同時(shí)又得兼容老版本 PHP4 的一寫語法特征,初學(xué)者在學(xué)習(xí) PHP 時(shí),顯然就不再那么容易了。特別是 PHP 的面向?qū)ο?OOP)有很多自身獨(dú)特的功能,寫法上為了兼容老版本,本身就比較混亂;另外一點(diǎn),PHP 的 OOP 是 PHP4 以后才有的,它出生只是為了個(gè)人主頁,這導(dǎo)致 PHP 在面向?qū)ο蠓矫嫒糊垷o首,不同的框架在各方面寫法都不一致,這點(diǎn)學(xué)起來比其他語言更麻煩。
PHP 5.3 以后 static 關(guān)鍵詞加上了一個(gè) Late Static Bindings 后期靜態(tài)綁定功能,很好的彌補(bǔ)了 self 和 __CLASS__ 的局限性,并且能夠很好的處理靜態(tài)綁定的層級(jí)關(guān)系。摘自 PHP 官網(wǎng):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. 該功能相當(dāng)于 get_class($this); 。如下代碼示例:<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test(); // output B
?>
上面的例子是后期靜態(tài)綁定中最簡(jiǎn)單的一個(gè),static 后期靜態(tài)綁定會(huì)改變方法的域,同時(shí)在遇到了 self,parent 關(guān)鍵詞時(shí)會(huì)向上一級(jí)傳遞調(diào)用信息。詳細(xì)參考:http://php.net/manual/en/language.oop5.late-static-bindings.php。
PHP 5.3 以后除了后期綁定功能,在靜態(tài)屬性和方法的訪問上支持使用變量加上雙冒號(hào)操作符去訪問靜態(tài)成員。如下代碼示例:<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
上面的例子在 PHP 官網(wǎng)也有詳細(xì)描述,參考鏈接:http://php.net/manual/en/language.oop5.static.php。
總結(jié)
以上是生活随笔為你收集整理的php static与self,PHP5.3新特性static与self区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 油漆备案是什么部门(油漆备案)
- 下一篇: php作菜单,PHP制作下拉透明菜单