在PHP中使用静态方法有什么好理由?

Leo*_*rdo 14 php oop static-methods

有没有人有任何使用静态方法而不是动态的好例子?

Ste*_*hen 8

辛格尔顿:

class SingletonClass {
    private static $instance;
    private function __construct() { }
    public function __clone() {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
    public static function init() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }
    // other public, dynamic methods for singleton
}

$singleton = SingletonClass::init();
Run Code Online (Sandbox Code Playgroud)

跟踪实例数:

class CountMe {
    public static $instances = 0;
    public function __construct() {
        CountMe::$instances++;
    }
    public function __destruct() {
        CountMe::$instances--;
    }
}
$a = new CountMe();
$b = new CountMe();
echo CountMe::$instances; // outputs 2
Run Code Online (Sandbox Code Playgroud)

  • 换句话说:你不能这样做`$ var = new SingletonClass();`因为会抛出一个错误.但静态方法可以做到这一点`self :: $ instance = new $ c;`因为它可以访问私有构造函数. (2认同)

ken*_*ken 4

当您不需要访问实例成员时。