PHP Get name of child class in static function [du

2019-03-06 14:04发布

问题:

This question already has an answer here:

  • Getting the name of a child class in the parent class (static context) 9 answers
  • How can I get the classname from a static call in an extended PHP class? 6 answers

Is something like this possible?

<?
class A
{
   public static function fun()
   {
      var_dump(get_class(child)); //bool(false) //should return B
   }
}
class B extends A
{
   public static function fun()
   {
      parent::fun();
   }
}

B::fun();
?>

回答1:

<?php
class B extends A
{
   public static function fun()
   {
      parent::fun();
   }
}
class A
{
   public static function fun()
   {
      var_dump(get_called_class());
   }
}

B::fun();

http://php.net/manual/en/function.get-called-class.php



回答2:

As of PHP 5.3, there is get_called_class() for this purpose:

echo get_called_class(); // yields "B"


标签: php class