views:

36

answers:

1

Most likely an OO concept question/situation:

I have a library that I use in my program with source files available. I've realized I need to tailor the library to my needs, say I need to modify the behavior of a single functions F in class C, while leaving the original library's source intact, to be able to painlessly upgrade it when needed.

I realize I can make my own class C1 inherited from C, place it in my source tree, and write the function F how I see it fit, replacing all occurrences of

myObj = new C();

with

myObj = new C1();

throughout my code.

What is the 'proper' way of doing this? I suspect the inheritance method I described has problems, as the library in its internals would still use C::F instead of my C1::F, and it would be way cooler if I could still refer to C::F not some strange C1::F in my code.

For those that care - the language is PHP5, and I'm kinda OOP newbie :)

+1  A: 

I think subclassing is pretty much the best way to add functionality to an external library.

The alternative is the decorator pattern whereby you have to wrap every method of the C class. (There is a time and place for the decorator pattern, but I think this isn't it)

You say:

as the library in its internals would still use C::F instead of my C1::F

Not necessarily true. If you pass an instance of the C1 class to a library function, then any calls to method F of that object would still go through your C1::F method. The same also happens when the C class accesses its own method by calling $this->F() -- because it's still a C1 object. This property is called polymorphism

Of course this does not apply when the library's code itself instantiates a new object of class C.

intgr