幾個PHP的靜態方法的程式例子_PHP教程

來源:互聯網
上載者:User
靜態方法的規則和靜態變數是相同的。使用ststic關鍵字可以將方法標識為靜態方法,通過類的名稱和範圍限定操作符::可以訪問靜態方法。

靜態方法和非靜態方法之間有一個很重要的區別,就是在調用靜態方法時,我們不需要建立類的執行個體。

Program List:用類名作為參數

用類名作為參數可以解決非繼承的靜態問題。

  

程式運行結果:

I'm Apple

Program List:重寫基類方法

在衍生類別重寫基類的方法。

  

程式運行結果:

Apple's color is red

Program List:靜態數組的使用

靜態和const範圍都可以用::操作符訪問,如果你想使用::操作符訪問數組,你需要事先將數組聲明為靜態。

   'red', 'color2' => 'yellow');}class Apple{  public function __construct()  {    var_dump(Fruit::$color);  }}class Banana{  public function __construct()  {    Fruit::$color = FALSE;  }}new Apple();    // prints array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" } echo '
';new Banana();new Apple(); // prints bool(false)?>

程式運行結果:

array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" } bool(false)

Program List:再來一個單例模式

Static真的很酷,下面的程式示範了如何獲得一個已經存在的執行個體。

    value = $value;    }    public static function getInstance() {        if ( self::$instance == null ) {            echo "
new
"; self::$instance = new Singleton("values"); } else { echo "
old
"; } return self::$instance; }}$x = Singleton::getInstance();var_dump($x); // returns the new object$y = Singleton::getInstance();var_dump($y); // returns the existing object?>

程式運行結果:

newobject(Singleton)#1 (1) { ["value:private"]=> string(6) "values" } oldobject(Singleton)#1 (1) { ["value:private"]=> string(6) "values" }

http://www.bkjia.com/PHPjc/752389.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752389.htmlTechArticle靜態方法的規則和靜態變數是相同的。使用ststic關鍵字可以將方法標識為靜態方法,通過類的名稱和範圍限定操作符::可以訪問靜態方法...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.