note 101644 added to function.call-user-func-array

From: Date: Sat, 01 Jan 2011 00:23:30 +0000
Subject: note 101644 added to function.call-user-func-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-175382@lists.php.net to get a copy of this message
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) )); } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 24.17.62.219 ---- Manual Page -- http://www.php.net/manual/en/function.call-user-func-array.php Edit -- https://master.php.net/note/edit/101644 Del: integrated -- https://master.php.net/note/delete/101644/integrated Del: useless -- https://master.php.net/note/delete/101644/useless Del: bad code -- https://master.php.net/note/delete/101644/bad+code Del: spam -- https://master.php.net/note/delete/101644/spam Del: non-english -- https://master.php.net/note/delete/101644/non-english Del: in docs -- https://master.php.net/note/delete/101644/in+docs Del: other reasons-- https://master.php.net/note/delete/101644 Reject -- https://master.php.net/note/reject/101644 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#175382) next »