靜態方法的規則和靜態變量是相同的。使用ststic關鍵字可以將方法標識為靜態方法,通過類的名稱和作用域限定操作符::可以訪問靜態方法。
靜態方法和非靜態方法之間有一個很重要的區別,就是在調用靜態方法時,我們不需要創建類的實例。
用類名作為參數可以解決非繼承的靜態問題。
<?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");
?>
程序運行結果:
I'm Apple
在派生類重寫基類的方法。
<?php
class Fruit
{
static function Foo ( $class = __CLASS__ )
{
call_user_func(array($class, 'Color'));
}
}
class Apple extends Fruit
{
static function Foo ( $class = __CLASS__ )
{
parent::Foo($class);
}
static function Color()
{
echo "Apple's color is red";
}
}
Apple::Foo(); // This time it works.
?>
程序運行結果:
Apple's color is red
靜態和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)
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" }