oop - PHP Getting a reference through a constructor? -
i wondering if possible while using keyword 'new' return reference existing object instead of new object. , if not, best way avoid co-existence of objects same parameters?
i have class arguments on constructor. if using arguments similar ones of existing instance, i'd new object reference existing one. possible? understand different singleton in case can have several instances of same class, not several instances using same parameters.
class myclass{ public $signature; /* unique signature connection */ public static $instances = array(); /* array of references connection */ private static function singleton($cfg,$inst){ $signature = sha1(serialize($cfg)); foreach ( self::$instances $obj ) { if ( $obj->signature == $signature ) return $obj; } array_push(self::$instances,$inst); return true; } function __construct($myparam){ if ( is_object(self::singleton($myparam,$this) ) // here i'd $this become ref of existing object else { $this->signature = $myparam; // construct new object } } } $e1 = new myclass(1); $e2 = new myclass(2); $e3 = new myclass(1); // $e3 should reference $e1
first few facts:
- the constructor can never return value.
- $this cannot reassigned (it in php 4 wasn't intended, , undocumented)
conclusion:
- use factory methods or delegation.*
* there slight difference between two, , using delegation $a!=$b, using factory methods $a === $b (see below)
delegation example:
// declare delegate wrapped delegationclass // * public methods/properties accessible class myclass { public $a; public function a($a) { echo "this a(\$a=$a)\n"; } } class mydelegationclass { static protected $_delegation = 'myclass'; // define delegate static protected $_i = array(); // instances protected $_l = null; // delegation link public function __construct($n) { if (!array_key_exists($n,self::$_i)) { // ensures instance created self::$_i[$n] = new self::$_delegation; } $this->_l = self::$_i[$n]; // link delegate } public function __get($v) { return $this->_l->$v; // property delegate link } public function __set($k,$v) { return $this->_l->$k = $v; // set property on delegate link } public function __call($f,$p) { // call method on delegate link return call_user_func_array(array($this->_l,$f),$p); } } // $a != $b, $a->a === $b->a $a = new mydelegationclass(1); $b = new mydelegationclass(1); factory class example:
class myfactoryclass { static protected $_i = array(); // instances public static function newmyclass($n) { if (!array_key_exists($n,self::$_i)) { // ensures instance created self::$_i[$n] = new myclass; } return self::$_i[$n]; // return instance } } // $a === $b $a = myfactoryclass::newmyclass(1); $b = myfactoryclass::newmyclass(1);
Comments
Post a Comment