PHP: 静态方法

自: http://www.nowamagic.net/php/php_StaticMethods.php 静态方法的规则和静态变量是相同的。使用ststic关键字能够将方法标识为静态方法,经过类的名称和做用域限定操做符::能够访问静态方法。php

静态方法和非静态方法之间有一个很重要的区别,就是在调用静态方法时,咱们不须要建立类的实例。数组

Program List:用类名做为参数ui

用类名做为参数能够解决非继承的静态问题。this

<?php class Fruit { public static $category = "I'm fruit"; static function find($class) { $vars = get_class_vars($class) ; echo $vars['category'] ; } } class Apple extends Fruit { public static $category = "I'm Apple"; } Apple::find("Apple"); ?>.net

程序运行结果: I'm Applecode

Program List:重写基类方法继承

在派生类重写基类的方法。作用域

class Fruit { static function Foo ( $class = CLASS ) { call_user_func(array($class, 'Color')); } }get

class Apple extends Fruit { static function Foo ( $class = CLASS ) { parent::Foo($class); }string

static function Color()
{
   	echo "Apple's color is red";
}

}

Apple::Foo(); // This time it works. ?>

程序运行结果: Apple's color is red

Program List:静态数组的使用

静态和const做用域均可以用::操做符访问,若是你想使用::操做符访问数组,你须要事先将数组声明为静态。

<?php class Fruit { static $color = array('color1' => '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 '<br />'; new Banana(); new Apple(); // prints bool(false) ?>

程序运行结果: array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" } bool(false)

Program List:再来一个单例模式

Static真的很酷,下面的程序演示了如何得到一个已经存在的实例。

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

程序运行结果: new object(Singleton)#1 (1) { ["value:private"]=> string(6) "values" } old object(Singleton)#1 (1) { ["value:private"]=> string(6) "values" }

相关文章
相关标签/搜索