Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

PHP : Get Class Name

By editor , 10 June, 2017
Question

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();

Tags

  • Module
  • Code
  • PHP
Php OOP - Examples and Tips

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer