Page 1 of 1
get_class inheritance question
Posted: Tue Sep 20, 2005 9:41 pm
by sunfish62
Say I have a base class (BaseClass) that includes a method to reveal its class (get_class):
class BaseClass {
...
function get_class() { return get_class(); }
}
Now, if I have an inherited class (BabyClass), I expect that 'BabyClass' will be returned when I use the get_class method:
class BabyClass extends BaseClass {
function BabyClass() {
echo $this->get_class(); // This should return BabyClass, but ...
}
}
However, my experience is that it returns BaseClass instead. Am I going crazy? Is there a workaround?
Posted: Tue Sep 20, 2005 10:44 pm
by feyd
call get_class() itself

Posted: Wed Sep 21, 2005 4:25 pm
by sunfish62
Well okay. But my reason for asking this is that I want a base error routine that identifies the class and function that caused the problem. That's why the get_class is embedded in the base class, and also why I want the name of the current class.
Certainly, I can (and have) manually set variables with the current class and function in each of the objects I have written so far. I was hoping to find a reliable way NOT to have to remember to put these commands into every single function I write. That seems to defeat the idea of object inheritance.
Regardless, your answer begs the question. If I instantiate a BabyClass object, the object is of type BabyClass--NOT BaseClass. So the get_class function (returning BaseClass) is returning the wrong value.
In my actual code, BaseClass is abstract--it **can't** exist. So PHP shouldn't ever tell me that I have an object of type BaseClass. And yet it does. That seems like a bug.
I will look for some other way to test the active class and function, since get_class is flawed.
Posted: Wed Sep 21, 2005 4:29 pm
by sweatje
try
Code: Select all
...
function get_class() { return get_class($this); }
Posted: Wed Sep 21, 2005 4:35 pm
by feyd
an "abstract" class in php5 can have implementation code, FYI.
Code: Select all
[feyd@home]>php -r "abstract class foo { function foob() { echo 'inside '.get_class().'::'.__FUNCTION__.chr(13); } } class bar extends foo { } $boo = new bar(); $boo->foob();"
inside foo::foob
Posted: Wed Sep 21, 2005 5:13 pm
by sunfish62
feyd:
You said:
an "abstract" class in php5 can have implementation code, FYI.
Meaning, what?
sweatje:
Where are you placing this? In the base class, or the inherited class?
Posted: Wed Sep 21, 2005 5:16 pm
by sweatje
sunfish62 wrote:
Where are you placing this? In the base class, or the inherited class?
In your base class. Just add the $this to the call.
Code: Select all
# php -r 'class A { function g() { return get_class($this); }} class B extends A { function t() { echo $this->g(); }}; $x = new B; $x->t();'
B
# php -v
PHP 5.0.3 (cli) (built: May 3 2005 03:50:13)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v2.0.3, Copyright (c) 1998-2004 Zend Technologies
with Xdebug v1.3.2, Copyright (c) 2002, 2003, by Derick Rethans