1

Say I have a class Core() where it will give me the instance of different classes depending on some initialization. Say that after initiating it, I get some class and then want to instantiate that. This is what I do:

$core = new Core(); // $core is further initiated $api = $core->getClass(); // This returns, for instance class Library_MyClass $class = new $api(); 

Is there a way to combine the last two steps into one? So for instance I say something like $class = new $core->getClass()()? Obviously what I wrote is wrong, but that is sort of what I want! Is that possible?

1
  • Normally you wouldn't have a class inside a class. You should have them separated I would think. Commented Aug 31, 2013 at 2:07

2 Answers 2

1

If this is some form of a factory you could do something like:

class Core { public function getClass() { return new Library_MyClass(); } } $core = new Core(); $class = $core->getClass(); 

However considering the name of the class Core I suspect you may be violating some SOLID principles here.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, it should be something like getLibraryInstance().
The name Core was an example. I have a different name. The problem with your solution is that I would want to give the class some initialization, i.e. new $class($param1, ...) and since depending on what class I get, I may or may not pass parameter(s), I rather that my Core only returns the class name and I instantiate it myself later.
The SOLID principles sound like something out of a motivational poster that they would have in Microsoft HQ. Experimenting with what you can do is half the fun (actually, more) in programming. Open-source especially :) new tricks -> new features later. Besides, I think I have an idea of what the poster wants to do, possibly make a catch all for loading php class files.
0

You might want to benefit from the use of dependency injection (considering a slight update applied to PeeHaa example)

class Core { public function getClass($api) { return new $api(); } } $core = new Core(); $apiInstance = $core->getClass('Library_MyClass'); 

This way you won't have to update the Core class whenever you would like it to provide you with an instance of another library class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.