Dynamic method allocation

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Dynamic method allocation

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
Post Reply