FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » How to create an instance from a class name
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
How to create an instance from a class name [message #177809] Sun, 22 April 2012 01:23 Go to previous message
Leonardo Azpurua is currently offline  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.

--
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: session question
Next Topic: Open Source Software Links
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Sun Nov 24 08:52:56 GMT 2024

Total time taken to generate the page: 0.04169 seconds