有什么方法可以限制 class 只创建 2 个对象

Is there any way to restrict a class to create only 2 objects

我知道单例对象设计模式。 如何允许 class 只创建 2 个不同的对象,那么它应该抛出一个错误。

可以执行以下操作:

  1. 为 class 创建静态变量。
  2. 初始化为0。
  3. 在构造函数中检查静态变量的值。如果超过 2,则抛出错误。否则继续。

@Ashwini 答案的代码版本:

<?php

class Limited {
    private static $amount = 0;

    public function __construct()
    {
            self::$amount++;
            if(self::$amount > 2) {
                    throw new Exception('Limit reached');
            }

            echo 'I am number ' . self::$amount . "\n";
    }
}

$obj1 = new Limited();
$obj2 = new Limited();

try {
    $obj3 = new Limited();
} catch(Exception $e) {
    $obj3 = null;
    unset($obj3);
}

您应该将每个新实例包装在一个 try-catch 中,以便在失败时删除该对象。