View previous topic :: View next topic |
Author |
Message |
MP_ n00b


Joined: 10 Nov 2003 Posts: 57 Location: Budapest, Hungary
|
Posted: Tue Jun 22, 2004 8:22 pm Post subject: PHP: create object of type by a string |
|
|
OK, so here's my problem:
I have several classes, and I want my script to create objects based on their name.
For example:
Code: |
class Example { ... }
[...]
$type = 'Example';
|
Now I want to know if there is a way to refer to the Example class directly from the string, like I can refer to a certain function or variable, whose name is stored in a string (create an object of type $type automatically). _________________ MP |
|
Back to top |
|
 |
Teetante Guru


Joined: 02 Mar 2004 Posts: 515 Location: Oldenburg/Germany
|
Posted: Tue Jun 22, 2004 11:50 pm Post subject: |
|
|
Thats no problem.
Code: |
$type = "Foo";
$ref = new $type;
|
This should work if the class $type has been declared before.
You could check that:
Code: |
$type = "Foo";
if(class_exists($type)
{
$ref = new $type;
}
else
{
$ref = NULL;
}
|
Semantically identical and shorter would be
Code: |
$type = "Foo";
$ref = (class_exists($type))?new $type:NULL;
|
_________________ ICQ #81510866 - http://the-gay-bar.com - MSN tante@emptiness.de
Occam's Razor:
-"Entia non sunt multiplicanda praeter necessitatem."- |
|
Back to top |
|
 |
MP_ n00b


Joined: 10 Nov 2003 Posts: 57 Location: Budapest, Hungary
|
Posted: Wed Jun 23, 2004 6:06 am Post subject: |
|
|
That's _exactly_ what I wanted. Thanks.
BTW if you use references, you need to use the previous one, which is also much easier to read.
Uh, one more thing:
Does the following also work?
Code: |
$type = 'Example';
$example_object = new $type($arg1, $arg2 ...);
|
_________________ MP |
|
Back to top |
|
 |
Teetante Guru


Joined: 02 Mar 2004 Posts: 515 Location: Oldenburg/Germany
|
Posted: Wed Jun 23, 2004 7:17 am Post subject: |
|
|
I would be more than surprised if it didn't  _________________ ICQ #81510866 - http://the-gay-bar.com - MSN tante@emptiness.de
Occam's Razor:
-"Entia non sunt multiplicanda praeter necessitatem."- |
|
Back to top |
|
 |
|