Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
PHP: create object of type by a string
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Portage & Programming
View previous topic :: View next topic  
Author Message
MP_
n00b
n00b


Joined: 10 Nov 2003
Posts: 57
Location: Budapest, Hungary

PostPosted: Tue Jun 22, 2004 8:22 pm    Post subject: PHP: create object of type by a string Reply with quote

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
View user's profile Send private message
Teetante
Guru
Guru


Joined: 02 Mar 2004
Posts: 515
Location: Oldenburg/Germany

PostPosted: Tue Jun 22, 2004 11:50 pm    Post subject: Reply with quote

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
View user's profile Send private message
MP_
n00b
n00b


Joined: 10 Nov 2003
Posts: 57
Location: Budapest, Hungary

PostPosted: Wed Jun 23, 2004 6:06 am    Post subject: Reply with quote

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
View user's profile Send private message
Teetante
Guru
Guru


Joined: 02 Mar 2004
Posts: 515
Location: Oldenburg/Germany

PostPosted: Wed Jun 23, 2004 7:17 am    Post subject: Reply with quote

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
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Portage & Programming All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum