How to Retrieve Class Name in PHP?

Barbara Streisand
Release: 2024-10-19 21:18:30
Original
811 people have browsed it

How to Retrieve Class Name in PHP?

Getting Class Name in PHP

In Java, one can obtain the name of a class using String className = MyClass.class.getSimpleName();. How can this be achieved in PHP, especially when working with Active Record and requiring a statement like MyClass::className?

Answer:

Since PHP 5.5, class name resolution is possible through ClassName::class. This feature enables you to determine the name of a class as follows:

<code class="php"><?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?></code>
Copy after login

If you want to utilize this feature within a class method, use static::class:

<code class="php"><?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?></code>
Copy after login

For earlier versions of PHP, you can employ get_class().

The above is the detailed content of How to Retrieve Class Name in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!