静态成员 #

一、静态属性 #

1.1 定义静态属性 #

php
<?php
class Counter
{
    public static int $count = 0;
    
    public static function increment(): int
    {
        return ++self::$count;
    }
}

echo Counter::$count;
Counter::$count = 10;
echo Counter::increment();

1.2 访问静态属性 #

php
<?php
class Config
{
    public static string $env = 'development';
    public static array $settings = [];
}

echo Config::$env;
Config::$env = 'production';
Config::$settings['debug'] = false;

二、静态方法 #

2.1 定义静态方法 #

php
<?php
class Math
{
    public static function square(int $n): int
    {
        return $n * $n;
    }
    
    public static function factorial(int $n): int
    {
        return $n <= 1 ? 1 : $n * self::factorial($n - 1);
    }
}

echo Math::square(5);
echo Math::factorial(5);

2.2 工厂方法 #

php
<?php
class User
{
    private function __construct(
        public readonly int $id,
        public readonly string $name
    ) {}
    
    public static function create(array $data): self
    {
        return new self($data['id'], $data['name']);
    }
    
    public static function fromJson(string $json): self
    {
        $data = json_decode($json, true);
        return self::create($data);
    }
}

$user = User::create(['id' => 1, 'name' => 'John']);

三、self vs static #

3.1 self #

php
<?php
class ParentClass
{
    public static function who(): string
    {
        return __CLASS__;
    }
    
    public static function test(): string
    {
        return self::who();
    }
}

class ChildClass extends ParentClass
{
    public static function who(): string
    {
        return __CLASS__;
    }
}

echo ChildClass::test();

3.2 static(后期静态绑定) #

php
<?php
class ParentClass
{
    public static function who(): string
    {
        return __CLASS__;
    }
    
    public static function test(): string
    {
        return static::who();
    }
}

class ChildClass extends ParentClass
{
    public static function who(): string
    {
        return __CLASS__;
    }
}

echo ChildClass::test();

四、实际应用 #

4.1 单例模式 #

php
<?php
class Database
{
    private static ?Database $instance = null;
    
    private function __construct() {}
    
    public static function getInstance(): Database
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

4.2 工具类 #

php
<?php
class Str
{
    public static function slug(string $text): string
    {
        return strtolower(preg_replace('/[^a-z0-9]+/i', '-', $text));
    }
    
    public static function random(int $length = 16): string
    {
        return substr(md5(uniqid()), 0, $length);
    }
}

五、总结 #

本章学习了:

  • 静态属性
  • 静态方法
  • self vs static
  • 后期静态绑定
  • 实际应用

下一章将学习魔术方法。

最后更新:2026-03-26