Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know about singleton object design pattern. How to allow a class to create only 2 different objects, then it should throw a error.

like image 403
Shailendra Sharma Avatar asked Oct 24 '25 12:10

Shailendra Sharma


1 Answers

A code version of @Ashwini's answer:

<?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);
}

You should wrap every new instance in a try-catch so you can delete the object if it fails.

like image 122
Jim Wright Avatar answered Oct 26 '25 04:10

Jim Wright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!