note 44259 added to language.oop

From: Date: Mon, 19 Jul 2004 22:04:36 +0000
Subject: note 44259 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-73631@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/language.oop.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+44259 Delete -- http://master.php.net/manage/user-notes.php?action=delete+44259&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+44259&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#73631) next »