一个类实例

yre*_*uta 1 php

有没有办法防止PHP脚本中同一个类的实例?

$user = new User();


$user2 = new User();  // I want to catch another instance of the user class and throw an exception
Run Code Online (Sandbox Code Playgroud)

我尝试创建一个静态变量并使用静态函数对其进行操作:

User::instance()
Run Code Online (Sandbox Code Playgroud)

但这并没有阻止我做:

$user = new User();
Run Code Online (Sandbox Code Playgroud)

irc*_*ell 6

在不更改对象语义的情况下,可以在构造函数中保留静态计数器.这不是单身,因为它不是全局可用的,只是可以实例化一次......

class Foo {
    private static $counter = 0;
    final public function __construct() {
        if (self::$counter) {
            throw new Exception('Cannot be instantiated more than once');
        }
        self::$counter++;
        // Rest of your constructor code goes here
    }
    // Rest of class
}
Run Code Online (Sandbox Code Playgroud)