Re: Object Inheritance, get_class() and a static function call

From: Date: Tue, 26 Jul 2005 19:42:19 +0000
Subject: Re: Object Inheritance, get_class() and a static function call
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-219377@lists.php.net to get a copy of this message
axel wrote:
Hello, following code won't work in the expected way: class ClassA { function getClassName() {
    return get_class($this); # [1]
} } class ClassB extends ClassA { } echo ClassB::getClassName(); this script echoes "Object" instead of "ClassB". but i would like to
either you tested some different code to what you posted above OR (your build of?) 5.0.3 is borked. I tested this on 5.0.2 and 5.0.4 and both did exactly what I expected, namely output nothing - $this is not defined when you call ClassB::getClassName() (because you make a static call) so nothing is the only logical output.
return the classname of the derived class without writing the method again. this will work:
??? it's not even valid php.
B = new ClassB(); echo ClassB->getClassName();
maybe you mean: class ClassA {function getClassName() { return get_class($this); }} class ClassB extends ClassA {} $B = new ClassB(); echo $B->getClassName(); which _does_ work but is fairly pointless because you already know the classname in order to be able to create the object in the first place.
i tried to use line [2] instead of [1] return get_class(self); # [2] but this only returns an empty string.
again this is what I expect to happen.
is there any solution for my problem?
I don't really see what the problem is, can you give some more real world detail on what you are trying/want to do? otherwise (re-)read this chapter: http://php.belnet.be/manual/en/language.oop5.php ... if you're _really_ into generic code then the reflection API is maybe you should look into. I have used reflection no and again, very useful stuff although to be honest I don't really grasp the concept/reasoning behind reflection properly (which means I have probably been 'misusing' it :-) rgds
i'm using PHP Version 5.0.3 (with Apache 1, Windows XP) greetings axel


« previous php.general (#219377) next »