Expand To Show Full Article
PHP Get Class Name with Advance Example

PHP Get Class Name with Advance Example

In this tutorial, we will learn the PHP get class by name with the help of an example.

What is get_class in PHP?

A get_class is a built-in function in PHP that is used to return the name of a class of an object.

Syntax Use:

get_class(object $object = ?): string

Parameters:

Object: It is the tested object. This parameter may be removed inside a class.

Also read: PHP modulo Operator With Examples

Return Values

  • A get_class() function will return the name of the class of an object.
  • When the object is removed inside a class, then it will return the names.
  • When the object returns FALSE IT IS NOT an object.
  • It returns FALSE if object is not an object. When the object is avoided in inside a class, it will returned the names.

For Example:

<?php

class php {
    function tutorial()
    {
        echo "This is my program in tutorial " , get_class($this) , "\n";
    }
}


$live = new php();


echo "This tutorial is get class name in  " , get_class($live) , "\n";

$live->tutorial();

?>

Output:

This tutorial is get class name in example
This is my program in tutorial example

Read or Visit: Isset in PHP Function With Examples

Use Reflection Class to Get Class Name in PHP

The reflection class is a

Reflection Class is a short step to get a class name in PHP. We will create a class; Inside in this class, which is to make a function that will returns a new Reflection class.

Furthermore, a reflection class it must have its argument set to $this. Then, we will get the class name through the getShortName() function available within the Reflection class.

<?php
    // For Defining a class
    class Example {
        // This is the function that returns the class

        public function ExampleOfClassName() {
            return (new \ReflectionClass($this))->getShortName();
        }
    }

    // This is to make a new class name
    $example_class_name = new Example();

    // This is to get Get the class name
    echo $example_class_name->ExampleOfClassName();
?>

Output:

Example

Conclusion

To conclude, we already discuss the PHP get_class name, the syntax used, the parameters, the return values and the examples.

Leave a Comment