Re: variable object creating
| From: | Jochem Maas | Date: | Wed, 22 Jun 2005 09:38:59 +0000 |
| Subject: | Re: variable object creating | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-217393@lists.php.net to get a copy of this message | ||
olivier wrote:
Hi,I answered this also, but apparently I only replied to the OP... (reproduced here - minus the typos in my first post on this topic :-/) if (class_exists($className, false)) {
$obj = new $className($construct_params);} else {
die("Hack off mate.");
}
Try something like: $classname = "MyClass"; $construct_params = array("param1","param2","param3"); $return =null; if(class_exists($classname)){ $param=explode(" ',' ", $construct_param);this should be join() not explode(), but even then it won't work, and even if it did you would only be able to pass strings (i.e. no objects, arrays, resources, etc) for this you should probably be looking at call_user_func_array() e.g: class Test { public $v; function __construct($v = 1) { $this->v = $v; } } $className = "Test"; if (class_exists($className, false)) {
// I had to test this to see if it works! the first 2 attempts are bogus
// but you can run them to see what happens -- also the 3 attempt is a pretty
// weird construction and I would be interested to know if anybody has thoughts
// on calling the ctor in this way (essentially calling it twice)
//
// ATTEMPT 1
//$obj = call_user_func_array(array($className,"__construct"), array(3));
// ATTEMPT 2
//$obj = call_user_func_array(array(new $className,"__construct"), array(3));
// ATTEMPT 3
call_user_func_array(array(($obj = new $className),"__construct"), array(3));
} else {
die("Hack off mate.");
}
var_dump($obj);
# You must add here some security checks.... eval("$retrun = new $className($param)");typo! 'retrun' (I spell 'return' like that alot too :-) btw eval() sucks and is not really needed, although granted it's an easy/flexible solution in terms on being able to pass args to the ctor (constructor), my thought would be that the classes you wish to init this way should have a specific interface/design with regard to accepting ctor args. A very simple example: class Test { function __construct($args = array()) { extract((array) $args); } }
var_dump($return); } Hope this help! Olivier Le Mercredi 22 Juin 2005 05:33, Eli a écrit :oh and don't blindly accept whatever is sent by the form - sanitize the class name and args before you use them! best general resource for this kind [php-]thing is (IMHO) http://phpsec.org/ [ "Shifting Expectations" ;-) ]Hi, I want to create an object in a form that I get the class name and its parameters, and I need to create that object...
How can this been done? i.e: $classname = "MyClass"; $construct_params = array("param1","param2","param3"); /* Now create the object with the given classname and params... how? */ -thanks, Eli