How to get the class name on php ?
The structure of the examples are like:
namespace Drupal\mymodule\Tools;
class MyTools extends MyToolsBase {
...
}
...
class MyToolsBase {
public function showClass() {
$class_name = ....
echo $class_name;
}
}
PHP Get the class name of a object;
Methode 1.
This will retuen the full clas name including namespace.
$class_name = (new \ReflectionClass($theObject))->getName();
//Result : Drupal\mymodule\Tools\MyTools
Methide 2.
This will retuen the full clas name including namespace but not very usefull as already you have the object.
$class_name = MyToolsBase::class;
//Result : Drupal\mymodule\Tools\MyToolsBase
Get the class name of the currect PHP object;
Methode 1.
$class_name = __CLASS__;
//Result : Drupal\mymodule\Tools\MyTools
Methode 2.
$class_name = (new \ReflectionClass($this))->getName();
//Result : Drupal\mymodule\Tools\MyTools
Methode 3.
$class_name = static::class;
//Result : MyTools
Methode 4.
$class_name = self::class;
//Result : MyToolsBases
Get class name without namespace on PHP.
Methode 1. (This methode is very fast)
$class_name = (new \ReflectionClass($this))->getShortName();
//Result : MyTools
Methode 2.
$class_name = array_pop(explode('\\', __CLASS__));
//Result : MyToolsBase
Methode 2.
$class_name = array_pop(explode('\\', __CLASS__));
//Result : MyToolsBase
Methode 3.
$class_name = array_pop(explode('\\', self::class));
//Result : MyToolsBase
Methode 4.
$class_name = array_pop(explode('\\', static::class));
//Result : MyTools
The PHP Object (POO) Reflection Class
ReflectionClass
$object = (new \ReflectionClass($this));
Get the Doc comments
$value = (new \ReflectionClass($this))->getDocComment();
Get file name
$value = (new \ReflectionClass($this))->getFileName();
Get the namespace
$value = (new \ReflectionClass($this))->getNamespaceName()
;
Comments