I know about singleton object design pattern. How to allow a class to create only 2 different objects, then it should throw a error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With