PHP的静态方法介绍
静态方法的规则和静态变量是相同的。使用ststic关键字可以将方法标识为静态方法,通过类的名称和作用域限定操作符::可以访问静态方法。
静态方法和非静态方法之间有一个很重要的区别,就是在调用静态方法时,我们不需要创建类的实例。
Program List:用类名作为参数
用类名作为参数可以解决非继承的静态问题。
03 |
publicstatic$category= "I'm fruit"; |
05 |
staticfunctionfind($class) |
07 |
$vars= get_class_vars($class) ; |
08 |
echo$vars['category'] ; |
12 |
classApple extendsFruit { |
13 |
publicstatic$category= "I'm Apple"; |
程序运行结果:
Program List:重写基类方法
在派生类重写基类的方法。
04 |
staticfunctionFoo ( $class= __CLASS__) |
06 |
call_user_func(array($class, 'Color')); |
10 |
classApple extendsFruit |
12 |
staticfunctionFoo ( $class= __CLASS__) |
19 |
echo"Apple's color is red"; |
23 |
Apple::Foo(); // This time it works. |
程序运行结果:
Program List:静态数组的使用
静态和const作用域都可以用::操作符访问,如果你想使用::操作符访问数组,你需要事先将数组声明为静态。
04 |
static$color= array('color1'=> 'red', 'color2'=> 'yellow'); |
09 |
publicfunction__construct() |
11 |
var_dump(Fruit::$color); |
17 |
publicfunction__construct() |
23 |
newApple(); // prints array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" } |
26 |
newApple(); // prints bool(false) |
程序运行结果:
1 |
array(2) { ["color1"]=> string(3) "red"["color2"]=> string(6) "yellow"} |
Program List:再来一个单例模式
Static真的很酷,下面的程序演示了如何获得一个已经存在的实例。
04 |
privatestatic$instance=null; |
07 |
privatefunction__construct($value) { |
08 |
$this->value = $value; |
11 |
publicstaticfunctiongetInstance() { |
12 |
if( self::$instance== null ) { |
14 |
self::$instance= newSingleton("values"); |
19 |
returnself::$instance; |
24 |
$x= Singleton::getInstance(); |
25 |
var_dump($x); // returns the new object |
26 |
$y= Singleton::getInstance(); |
27 |
var_dump($y); // returns the existing object |
程序运行结果:
2 |
object(Singleton)#1 (1) { ["value:private"]=> string(6) "values"} |
4 |
object(Singleton)#1 (1) { ["value:private"]=> string(6) "values"} |