note 35685 added to function.eval

From: Date: Thu, 11 Sep 2003 03:04:50 +0000
Subject: note 35685 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-56043@lists.php.net to get a copy of this message
You can use eval() to pass variable-length parameter lists to arbitrary functions by using func_get_args() to build the required code. This approach can sometimes be preferable to using an array. The example below defines a function capable of instantiating objects whose constructors expect different numbers of parameters. <?php function classFactory($classname) { $code = "return new {$classname}("; if (func_num_args() > 1) { $params = array_slice(func_get_args(),1); $c = count($params); for($i=0;$i<$c;++$i) { if ($i>0) { $code .= ','; } $code .= '$params[' . $i . ']'; } } $code .= ');'; return eval($code); } class Foo { function Foo($arg1,$arg2,$arg3) { echo "I am Foo, I expect 3 arguments...\n"; echo "arg1 = $arg1\n"; echo "arg2 = $arg2\n"; echo "arg3 = $arg3\n\n"; } } class Bar { function Bar($arg1) { echo "I am Bar, I expect 1 argument...\n"; echo "arg1 = $arg1\n\n"; } } $myFoo = classFactory('Foo',100,'moose',array(1,2,3)); $myBar = classFactory('Bar',4564); ?> ---- Manual Page -- http://www.php.net/manual/en/function.eval.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35685 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35685&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35685&report=yes

« previous php.notes (#56043) next »