camka
не самка
простите за назойливость. При попытке универсализировать все предыдущие решения застрял не таком:
вылетает сегментейшн фолт.
PHP:
<?php
error_reporting (E_ALL | E_STRICT);
class singletonException extends Exception {
public function __construct() {
//do nothing
}
}
abstract class Singleton {
public function __construct($name) {
if(isset(Factory::$instances[$name])) {
throw new singletonException();
} else {
Factory::$instances[$name] = $this;
}
}
}
final class Factory {
static $instances = array();
public function __call($class, $args) {
try {
$R = new ReflectionClass($class);
call_user_func_array(array($R, 'newInstance'), $args);
//new $class($class);
} catch (singletonException $e) {
//do nothing
}
return Factory::$instances[$class];
}
public static function get()
{
return new self;
}
}
class A extends Singleton
{
public $a;
public function __construct($a)
{
$this->a = $a;
parent::__construct(__CLASS__);
}
}
class B extends Singleton
{
public $b;
public $c;
public function __construct($b, $c)
{
$this->b = $b;
$this->c = $c;
parent::__construct(__CLASS__);
}
}
echo '<pre>';
$a1 = Factory::get()->A(1);
$a2 = Factory::get()->A(2);
$b1 = Factory::get()->B(3,4);
$b2 = Factory::get()->B(4,5);
var_dump($a1, $a2, $b1, $b2);
?>