How to create an instance from a class name [message #177809] |
Sun, 22 April 2012 01:23 |
Leonardo Azpurua
Messages: 46 Registered: December 2010
Karma:
|
Member |
|
|
Hi,
I am working on a class to generate a report from specs contained in a user
defined file.
A section on the file defines a form in which the user will input parameters
for the report. This form may contain different kinds of INPUT items, namely
FECHA (date), NUMERO (number), TEXT, SELECT, LISTA (select with multiple
options) or CODIGO (an items code, with the ability to search by
name/description). Each item is defieed in a class that knows how to parse
the definitions and generate the corresponding HTML/Script code.
Each class name is made of a preffix ("procesador") plus the type of item
(e.g. "procesadorFECHA").
Initially I used a switch statement in order to build each class:
switch ($token->value)
{
case "TEXT":
$proc = new procesadorTEXT();
break;
case "NUMBER":
$proc = new procesadorNUMERO();
break;
...
default:
die("Invalid INPUT type ...");
}
$proc->go($tokens, $lineNumber, $this->context);
I recall having read somewhere an example of PHP instantiatiting an object
from a class name, but I forgot both the workings and the source of the
example. I made a few attempts with ReflectionClass, but I couldn't find a
solution, so this is what I did:
$className = "procesador" . $token->value;
$newFunc = create_function("", "return new " . $className . "();");
$proc = $newFunc();
$proc->go($tokens, $lineNumber, $this->laEmpresa);
unset($newFunc);
It works, but I would like to know whether it will produce any unexpected
behaviour when the component enters in production, and if there is a better
(cleaner) way to do it.
Thanks.
--
|
|
|