note 101644 deleted from function.call-user-func-array by danbrown

From: Date: Sat, 01 Jan 2011 00:46:08 +0000
Subject: note 101644 deleted from function.call-user-func-array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-175383@lists.php.net to get a copy of this message
Note Submitter: jpadvo at gmail dot com ---- With a bit of magic, you can use call_user_func_array to call an objects constructor -- even if it has required arguments. This can be a very useful trick in a factory class. <?php // First, create an empty, vanilla stdClass object $object = (object) array( ); // Then change it to the class you want. Notice that we have created a // $classname object without calling $classname->__construct() ! $this->changeClass( $object, $classname ); // Now you can call the constructor, with all the required arguments in place. Bam! $result = call_user_func_array( array( $object, "__construct" ), $args ); // changeClass is adapted from the example at: // http://www.jasny.net/articles/a-dark-corner-of-php-class-casting/ function changeClass(&$obj, $newClass) { $obj = unserialize(preg_replace // change object into type $new_class ( "/^O:[0-9]+:\"[^\"]+\":/i", "O:".strlen($newClass).":\"".$newClass."\":", serialize($obj) )); } ?>

« previous php.notes (#175383) next »