Page 1 of 1

Dynamic method allocation

Posted: Thu Jul 19, 2007 12:33 am
by Benjamin
I have been researching extends and factory methods but I don't think they do exactly what I'm looking for.

If I have a class foo..

Code: Select all

class foo
{
    public function foo_function()
    {

    }
}
And class bar..

Code: Select all

class bar extends foo
{
    public function bar_function()
    {

    }
}
That is nice, but I'm assuming that if I create an instance of foo, the bar_function() method won't exist, and if I create an instance of bar, I'm getting an instance of bar that has methods inherited from the foo class.

The way I need it to work is for me to create an instance of foo, then somehow add methods from bar to the foo instance.

Is this possible? If not I can create a workaround. I'm just looking for the best solution.

Posted: Thu Jul 19, 2007 4:44 am
by feyd
Methods cannot be dynamically created after the class is defined. You would need to define a new class dynamically... That would probably be a code smell.

Posted: Thu Jul 19, 2007 5:40 am
by Jenk
Why *must* it be an instance of Foo, with methods from Bar?

If you are trying to circumvent interfacing, you're a) worrying about a non-issue:

Code: Select all

class foo {}
class bar extends foo {}

$obj = new bar;

echo ($obj instanceof foo); // true
b) trying to circumvent the entire purpose of interfacing.

Or, you need to refactor your code to separate the functionality you need (for the given scenario,) from that you don't.

Posted: Thu Jul 19, 2007 8:24 am
by Benjamin
It's a unique variant of the factory pattern, and it's very clean. I'll use the __call method and have it reload itself.

Posted: Thu Jul 26, 2007 6:30 pm
by Ollie Saunders
This is this a design pattern?! Can you provide any information about the pattern.
Why do you want to do this? Are you in fact trying to write a dependency injector to a __call() interface?

Posted: Fri Jul 27, 2007 2:17 am
by Chris Corbyn
I have to agree that from what I've heard so far this seems like a smell, but I don't know all the facts. Perhaps you could look into Mixins. Mxins are really intended to "emulate" multiple inheritance but because of the way they work you could achieve what you want.