note 69433 added to language.constants.predefined
| From: | stangelanda at gmail dot com | Date: | Wed, 06 Sep 2006 04:17:51 +0000 |
| Subject: | note 69433 added to language.constants.predefined | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-116740@lists.php.net to get a copy of this message | ||
claude noted that __CLASS__ always contains the class that it is called in, if you would rather have
the class that called the method use get_class($this) instead. However this only works with
instances, not when called statically.
<?php
class A {
function showclass() {
echo get_class($this);
}
}
class B extends A {}
$a = new A();
$b = new B();
$a->showclass();
$b->showclass();
A::showclass();
B::showclass();
//results in "a", "b", false, false
?>
I tried keeping track of the class manually within the properties, but the following doesn't
work either:
<?php
class A {
var $class = __CLASS__;
function showclass() {
echo $this->class;
}
}
class B extends A {
var $class = __CLASS__;
}
//results in "a", "b", NULL, NULL
?>
The best solution I could come up with was using debug_backtrace. I assume there is a better way
somehow, but I can't find it. However the following works:
<?php
class A {
function showclass() {
$backtrace = debug_backtrace();
echo $backtrace[0]['class'];
}
}
class B extends A {}
//results in "a", "b", "a", "b"
?>
----
Server IP: 216.194.113.175
Probable Submitter: 207.32.22.145
----
Manual Page -- http://www.php.net/manual/en/language.constants.predefined.php
Edit -- https://master.php.net/note/edit/69433
Del: integrated -- https://master.php.net/note/delete/69433/integrated
Del: useless -- https://master.php.net/note/delete/69433/useless
Del: bad code -- https://master.php.net/note/delete/69433/bad+code
Del: spam -- https://master.php.net/note/delete/69433/spam
Del: non-english -- https://master.php.net/note/delete/69433/non-english
Del: in docs -- https://master.php.net/note/delete/69433/in+docs
Del: other reasons-- https://master.php.net/note/delete/69433
Reject -- https://master.php.net/note/reject/69433
Search -- https://master.php.net/manage/user-notes.php