Method inheritance and parent classes

php.internals

Christian Weiske

20 years ago
Hello all, I recently had a problem that could be solved, but in an ugly way: Class B extended Class A. Both classes define a method with the same name. B called A's constructor, and A called $this->method(). This executed B::method(), not A::method() as you would expect it. <?php class A { function __construct() { $this->build(); } function build() { echo "buildA "; } } class B extends A { function __construct() { parent::__construct(); $this->build(); } function build() { echo "buildB "; } } new B(); ?> output is: "buildB buildB " expected would be: "buildA buildB " I suggest changing the behavior of php to never call methods of classes that are added by subclasses, only own ones or inherited ones.
-- Regards/MfG, Christian Weiske

Jason Sweat

20 years ago
On 8/4/06, Christian Weiske <cweiske@cweiske.de> wrote:
> I suggest changing the behavior of php to never call methods of classes > that are added by subclasses, only own ones or inherited ones.
Thus rendering the entire Template Method design pattern useless? http://home.earthlink.net/~huston2/dp/templateMethod.html
-- Regards, Jason http://blog.casey-sweat.us/

Richard Lynch

20 years ago
On Fri, August 4, 2006 11:46 am, Christian Weiske wrote:
> I recently had a problem that could be solved, but in an ugly way: > Class B extended Class A. Both classes define a method with the same > name. B called A's constructor, and A called $this->method(). This > executed B::method(), not A::method() as you would expect it.
Most OOP people expect it to run B::method() That's rather the whole point of inheritence and subclasses. If you need to override it, you might be able to use A::method()... Though the OO purists have made that illegal now, I think. :-; There may be some kind of get_method() function on a class that you could use like: $function = get_method('A', 'method'); user_call_func(array($this, $function));
-- Like Music? http://l-i-e.com/artists.htm

Marian Kostadinov

20 years ago
use self::build() or A::build() for that case 2006/8/4, Christian Weiske <cweiske@cweiske.de>: