Page 1 of 1

Creation of an instance knowing class name

Posted: Mon Apr 24, 2006 6:43 am
by khainodd
Hello all,

I'm new to PHP, and I'd be very grateful if someone could give me a hand with a doubt I have.

I'm writing a program in which I need to create an instance of a class which name is entered by the user. The name can be anything, so I can't do something like a switch. I know in Java there is a ClassLoader class that allows to create an instance passing the class name, but I don't know if this exists in PHP or if there's a workaround to simulate it.

Thank you for your responses, in advance :)

And sorry if my post is not very clear, but I'm not english :roll:

Posted: Mon Apr 24, 2006 6:52 am
by Ollie Saunders
You can have variable object name not class names.
What are you trying to achieve with having a variable class name?

Posted: Mon Apr 24, 2006 6:58 am
by khainodd
ole wrote:You can have variable object name not class names.
What are you trying to achieve with having a variable class name?
I'm trying to create a little framework that allows to use different classes to implement model actions, all of this classes are specified in an XML file. Something like this:

<action name="insert" class="InsertAction"/>

Posted: Mon Apr 24, 2006 7:44 am
by Chris Corbyn

Code: Select all

class foo
{
 //
}

$className = 'foo';

$obj = new $className;
It's probably best to re-think your design a bit and have the objects instantiated from outside of your class, and then passed by reference using a method (or the constructor).

Posted: Mon Apr 24, 2006 8:11 am
by Ollie Saunders
It's probably best to re-think your design a bit and have the objects instantiated from outside of your class, and then passed by reference using a method (or the constructor).
Yes. How about:

Code: Select all

<insert name="foo" />
and then in the XML parser just use logic or d11wtq's example to create objects. I would try to ensure that all your classes implement the same interface where possible so you can change an insert action to an update action as transparently as possible.

Posted: Mon Apr 24, 2006 8:11 am
by khainodd
This works perfectly. Thank you for your help! :D

Posted: Mon Apr 24, 2006 9:35 am
by khainodd
Yes. How about:

Code: Select all

<insert name="foo" />
and then in the XML parser just use logic or d11wtq's example to create objects. I would try to ensure that all your classes implement the same interface where possible so you can change an insert action to an update action as transparently as possible.
Yes, that is my approach. All actions extends a superclass, so they can be used independently in any part of the code. Thanks a lot :D