PHP Function Reference

PHP get_class() Function



The PHP get_class() function returns the name of the class of the given object.

Syntax

get_class(object)

Parameters

object

Optional. Specify the tested object. This parameter may be omitted when inside a class.

Note: Explicitly passing null as the object is no longer allowed as of PHP 7.2.0. The parameter is still optional and calling this function without a parameter from inside a class works, but passing null now emits an E_WARNING notice.

Return Value

Returns the name of the class of which object is an instance. Returns false if object is not an object.

If object is omitted when inside a class, the name of that class is returned.

If the object is an instance of a class which exists in a namespace, the qualified namespaced name of that class is returned.

Exceptions

Raises an E_WARNING level error if the function is called with anything other than an object.

Example: using get_class()

The example below shows the usage of get_class() function.

<?php
class myClass {
  function name() {
    echo "Class name (internal call): ".get_class($this)."\n";
  }
}

//creating an object
$myObject = new myClass();

//external call
echo "Class name (external call): ".get_class($myObject)."\n";

//internal call
$myObject->name();
?>

The output of the above code will be:

Class name (external call): myClass
Class name (internal call): myClass

Example: using get_class() in superclass

Consider the example below where this function is used in a superclass.

<?php
abstract class bar {
  public function __construct() {
    var_dump(get_class($this));
    var_dump(get_class());
  }
}

class foo extends bar {
}

new foo;
?>

The output of the above code will be:

string(3) "foo"
string(3) "bar"

Example: using get_class() with namespaced classes

Consider the example below where this function is used with namespaced classes.

<?php
namespace Foo\Bar;

class Baz {
  public function __construct() {
  }
}

$baz = new \Foo\Bar\Baz;

var_dump(get_class($baz));
?>

The output of the above code will be:

string(11) "Foo\Bar\Baz"

❮ PHP Classes/Objects Reference