靜態成員屬於「類別本身」,而非某個實例。所有實例共享同一份靜態屬性,靜態方法不依賴 $this。
<?php
class Counter {
public static $count = 0;
public function __construct() {
self::$count++; // 類別內部用 self:: 或 類別名::
}
public static function getCount() {
return self::$count;
}
}
$c1 = new Counter();
$c2 = new Counter();
echo Counter::$count; // 2
echo Counter::getCount(); // 2
public static $varClassName::$var 或 self::$var(類別內)、static::$var(晚期靜態綁定)$this->var 存取<?php
class Math {
public static function add($a, $b) {
return $a + $b; // 無 $this,不可存取非靜態成員
}
}
echo Math::add(1, 2); // 3
// 亦可透過實例呼叫(不建議)
$m = new Math();
echo $m->add(3, 4); // 7,但內部無 $this
public static function name()$this<?php
class Test {
public function nonStatic() {
echo 'non-static: ' . ($this ? 'has $this' : 'no $this');
}
public static function staticM() {
echo 'static: ' . ($this ? 'has $this' : 'no $this');
}
}
$t = new Test();
$t->nonStatic(); // non-static: has $this
$t->staticM(); // static: no $this (PHP 5.3+ 嚴格模式下會警告)
Test::staticM(); // static: no $this
<?php
class Config {
const VERSION = '1.0';
const DB_TYPE = 'mysql';
}
echo Config::VERSION; // 1.0
// 常數隱含 static,不可用 public static const
<?php
class A {
public static function who() { echo __CLASS__; }
public static function test() { self::who(); } // 綁定 A
}
class B extends A {
public static function who() { echo __CLASS__; }
}
B::test(); // 輸出 A (self:: 綁定定義處)
// 使用 static:: 實現晚期綁定
class A2 {
public static function test() { static::who(); }
}
class B2 extends A2 {
public static function who() { echo __CLASS__; }
}
B2::test(); // 輸出 B2
static:: 而非 self::