類別名::成員 存取<?php
class User {
private static $count = 0; // 靜態屬性
public function __construct() {
self::$count++; // 內部存取:self::
}
public function getCount() {
return self::$count;
}
public function __destruct() {
self::$count--;
}
}
$user1 = new User();
$user2 = new User();
$user3 = new User();
echo "Current users: " . $user1->getCount() . "\n"; // 3
unset($user3);
echo "Current users: " . $user1->getCount() . "\n"; // 2
?>
<?php
class Math {
public static $pi = 3.14;
}
$r = 3;
echo "Area: " . Math::$pi * $r * $r . "\n"; // 28.26
// 運行時動態修改(影響所有後續存取)
Math::$pi = 3.141592653589793;
echo "Precise Area: " . Math::$pi * $r * $r . "\n"; // 28.2743338823
?>
static $x = 1;、static $x = 'str';、static $x = SOME_CONST;static $x = 1+1;、static $x = func();、static $x = new Class(); → Parse Errorreadonly:public static readonly string $version = '1.0';<?php
class Math {
public static function max($a, $b) {
return $a > $b ? $a : $b;
}
public static function max3($a, $b, $c) {
// 內部調用同類靜態方法:推薦 self::
$max = self::max($a, $b);
$max = self::max($max, $c);
return $max;
}
}
echo Math::max(99, 88); // 99
echo Math::max3(99, 77, 88); // 99
?>
<?php
class Circle {
public static $pi = 3.14;
public static function area($r) {
// 推薦 self:: 而非 類別名::
return $r * $r * self::$pi;
}
}
echo Circle::area(3); // 28.26
?>
<?php
class Circle {
public $pi = 3.14; // 非靜態
public static function area($r) {
return $r * $r * self::$pi; // Fatal Error: Undefined class constant 'pi'
}
}
?>
<?php
class Circle {
public $pi = 3.14;
public static function area($r) {
return $r * $r * $this->pi; // Fatal Error: Using $this when not in object context
}
}
?>
<?php
class Math {
public $pi = 3.14;
public function max($a, $b) { // 非靜態
echo self::$pi; // 這裡 self::$pi 會報錯,因為 $pi 非靜態
return $a > $b ? $a : $b;
}
public static function max3($a, $b, $c) {
// 以 static:: 呼叫非靜態方法 → PHP 視為靜態調用
$m = self::max($a, $b); // 此時 max() 在靜態語境執行
return self::max($m, $c);
}
}
Math::max3(1,2,3); // Fatal Error: Access to undeclared static property: Math::$pi
?>
規則:以 self::/類別名::/static:: 呼叫非靜態方法時,該方法在靜態語境執行,內部不可使用 $this、不可存取非靜態屬性。
static:: vs self::<?php
class Base {
public static function who() {
echo __CLASS__ . "\n";
}
public static function test() {
self::who(); // 編譯期綁定 → Base
static::who(); // 運行期綁定 → 實際調用類別
}
}
class Derived extends Base {
public static function who() {
echo __CLASS__ . "\n";
}
}
Derived::test();
// 輸出:
// Base (self::)
// Derived (static::)
?>
<?php
class Database {
private static $instance = null;
private $pdo;
private function __construct() {
$this->pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
}
// 禁止克隆
private function __clone() {}
// 禁止反序列化
public function __wakeup() {
throw new Exception("Cannot unserialize singleton");
}
public static function getInstance(): self {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getPdo(): PDO {
return $this->pdo;
}
}
// 使用
$pdo = Database::getInstance()->getPdo();
?>
<?php
class User {
private $id, $name, $email;
private function __construct($id, $name, $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
public static function create(string $name, string $email): self {
// 驗證、生成 ID、資料庫寫入...
$id = random_int(10000, 99999);
return new self($id, $name, $email);
}
public static function fromArray(array $data): self {
return new self($data['id'], $data['name'], $data['email']);
}
}
$user = User::create('Alice', 'alice@example.com');
?>
| 場景 | 關鍵字 | 存取方式 | 注意事項 |
|---|---|---|---|
| 共享計數器/配置/快取 | static 屬性 | self::$prop / Class::$prop | 僅字面值初始化,記憶體單份共享 |
| 工具方法/無狀態邏輯 | static 方法 | self::method() / Class::method() | 不可用 $this、不可存取非靜態成員 |
| 繼承體系中多型調用 | static:: | static::method() | Late Static Binding,運行期解析實際類別 |
| 單例/工廠/註冊表 | static 方法 + 私有建構子 | Class::getInstance() | 控制實例化邏輯,全域唯一存取點 |
善用 static 能實現無狀態服務、全域共享狀態、受控實例化,但濫用會導致強耦合、難以測試、全域狀態汙染。原則:優先實例方法,需共享狀態或無狀態工具時再考慮 static,並配合依賴注入容器管理生命週期。