note 44259 deleted from language.oop by danbrown

From: Date: Sat, 07 Nov 2009 19:03:54 +0000
Subject: note 44259 deleted from language.oop by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162569@lists.php.net to get a copy of this message
Note Submitter: bishop ---- Say you have a factory method that needs to put data into an object before the constructor is called. This might be necessary, for example, if the factory class establishes a connection to a database and the manufactured object uses that connection in the constructor. Do something like this: <?php function &factory($class /* ... */) { // 1) get an object shell $obj = new stdClass(); // 2) "type cast" it to the desired class $tmp = explode(':', serialize($obj)); $tmp[1] = strlen($class); $tmp[2] = '"' . $class . '"'; $obj = unserialize(implode(':', $tmp)); // 3) copy construct the manufacturer into the manufacturee $obj->copyFrom($this); // 4) call the real constructor $args = func_get_args(); array_shift($args); // skip the class call_user_func_array(array (&$obj, $class), $args); return $obj; } ?> NOTE: The Editor's note in the "simon dot li at hongkong dot com" entry is misleading; it only works because the class names "foo" and "bar" are the same length. In general, you must change the first and second entries in serialized array as done above. Also NOTE: This typecasting business works if you have a function that takes an arbitrary number of arguments and you want to pass those arbitrary arguments into a constructed class. You can't just use call_user_func_array() in that case because 'new' is an operator, not a function.

« previous php.notes (#162569) next »