Home > php教程 > php手册 > PHP在类中获得当前class名称

PHP在类中获得当前class名称

WBOY
Release: 2016-06-21 09:04:59
Original
1345 people have browsed it

php 4.3以后新增了一个魔术常量__CLASS__,用来获得当前class名称。但是在下面的代码中,却不work。

class A {
 function showclass() {
     echo __CLASS__;
 }
}
class B extends A {}
 
A::showclass();
B::showclass();

这段代码会打出两个A,而不是预想中的AB。

下面这段代码,利用debug_backtrace来获得当前class名,可惜只能在php4上面work,到了php5以上,测试结果全部都是AA-___-

class A {
   function showclass() {
      $backtrace = debug_backtrace();
      echo $backtrace[0]['class'];
   }
}
 
class B extends A {}

补充一个可以在php4/php5下work的代码

class A {
 function showclass() {
    $backtrace = debug_backtrace();
    echo ((int)PHP_VERSION> 4) ?
        get_class($backtrace[0]['object']) : $backtrace[0]['class'];
 }
}
class B extends A {}



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template