How Can I Get a Class Name in PHP?

Mary-Kate Olsen
Release: 2024-10-19 21:19:29
Original
690 people have browsed it

How Can I Get a Class Name in PHP?

Getting Class Name in PHP

Similar to Java, PHP provides various methods to retrieve the class name.

Using ClassName::class

With PHP version 5.5 and above, class name resolution can be achieved using the ClassName::class syntax:

<code class="php">namespace Name\Space;

class ClassName {}

echo ClassName::class;</code>
Copy after login

Using get_class()

For older versions of PHP, the get_class() function can be used:

<code class="php">class MyClass {

}

$className = get_class(new MyClass());</code>
Copy after login

Using static::class (For Class Methods)

Within a class method, the static::class syntax can be used to retrieve the class name:

<code class="php">namespace Name\Space;

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

$obj = new ClassName();
echo $obj->getNameOfClass();</code>
Copy after login

The above is the detailed content of How Can I Get a 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!