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
Re: How to create an instance from a class name [message #177814 is a reply to message #177809] Sun, 22 April 2012 09:19 Go to previous messageGo to previous message
M. Strobel is currently offline  M. Strobel
Messages: 386
Registered: December 2011
Karma:
Senior Member
Am 22.04.2012 03:23, schrieb Leonardo Azpurua:
> 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.
>
> --

Just take the classname as variable in the new Operator:

class clase1 {
function buenos() {
echo "Bon día!\n";
}
}

class clase2 {
function buenos() {
echo "Buenos días!\n";
}
}

foreach (array(1,2) as $v) {
$cn = 'clase' . $v;
$c = new $cn();
$c->buenos();
}
#--------------------
Bon día!
Buenos días!


/Str.
[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:42:15 GMT 2024

Total time taken to generate the page: 0.04702 seconds