Page 1 of 1

How to create classes dynamically, maybe with call_user_func

Posted: Thu Nov 19, 2009 7:16 am
by vargadanis
hi,

I would like to create a modular website in which the modules would be nothing but classes. After registering the modules I would like to create new class objects. This would normally look like:

Code: Select all

 $var = new ClassName(); 
However at this point I have nothing else but the names of the objects and the included files that contain the Class definitions of the class. Something like this:

Code: Select all

 $var = 'ClassName';
require_once 'file/that/contains/ClassName/definition.php'; 
So after the require I would like to actually call ClassName. I have PHP 5, but not PHP 5.3. It's some version of PHP 5.2 or 5.1.
So what I'd like to see is something like:

Code: Select all

 $var = 'ClassName';
require_once 'file/that/contains/ClassName/definition.php';
$class = some_method ($var );
/* and from there on I'd like to be able to: */
$class->method1();
$class->method2();
I hope you guys can help me out here...

Re: How to create classes dynamically, maybe with call_user_func

Posted: Thu Nov 19, 2009 7:45 am
by iankent
What about something like:

Code: Select all

eval("\$newClass = new ".$className."();";
After that line you can then access $newClass as normal. You'd need to make sure all of the classes contained the same methods, properties etc that are accessed by your code.

Re: How to create classes dynamically, maybe with call_user_func

Posted: Thu Nov 19, 2009 7:51 am
by vargadanis
iankent wrote:What about something like:

Code: Select all

eval("\$newClass = new ".$className."();";
After that line you can then access $newClass as normal. You'd need to make sure all of the classes contained the same methods, properties etc that are accessed by your code.
Thanx, I am gonna try this approach as well.
As a sidenote, I saw on some google search hits another solution that seems to be working as well:

Code: Select all

$c = new $ClassVar();

Re: How to create classes dynamically, maybe with call_user_func

Posted: Thu Nov 19, 2009 7:53 am
by iankent
vargadanis wrote:Thanx, I am gonna try this approach as well.
As a sidenote, I saw on some google search hits another solution that seems to be working as well:

Code: Select all

$c = new $ClassVar();
If that does work its a much neater and probably safer method (and definately more efficient). Only use eval() if you need to, I have to say I wasn't aware of this method but it looks good :)