Quick actions

cmd+k|ctrl+k

Navigation

Languages

PHP 单例模式

Snippet info

Language

Php

Visibility

public

Author

mosi

Created

2018-11-21T03:54:30Z

Updated

2018-11-21T03:54:30Z

<?php

class Foo {
    static private $instances = [];

    /**
     * 禁止 new
     */
    protected function __construct() {}

    /**
     * 禁止 clone
     */
    final private function __clone() {}

    final static public function getInstance() {
        $class = get_called_class();

        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new static;
        }

        return self::$instances[$class];
    }
}

class Bar extends Foo {

}

$foo = Foo::getInstance();
$bar = Bar::getInstance();





INFO