get_class

(PHP 4, PHP 5, PHP 7, PHP 8)

get_classErmittelt den Klassennamen eines Objekts

Beschreibung

function get_class(object $object = ?): string

Ermittelt den Klassennamen für das übergebene object.

Parameter-Liste

object

Das zu untersuchende Objekt.

Hinweis:

Die explizite Übergabe von null als object ist von PHP 7.2.0 an nicht mehr erlaubt und erzeugt einen E_WARNING-Hinweis. Seit PHP 8.0.0 wird ein TypeError ausgegeben, wenn null verwendet wird.

Rückgabewerte

Gibt den Namen der Klasse zurück, von der object eine Instanz ist.

Ist object eine Instanz einer Klasse in einem Namensraum, wird der qualifizierte Name dieser Klasse zurückgegeben.

Fehler/Exceptions

Wenn get_class() mit etwas anderem als einem Objekt aufgerufen wird, wird ein TypeError erzeugt. Vor PHP 8.0.0 wurde ein Fehler der Stufe E_WARNING erzeugt.

Wenn get_class() ohne Parameter von außerhalb einer Klasse aufgerufen wird, wird ein Error erzeugt. Vor PHP 8.0.0 wurde ein Fehler der Stufe E_WARNING erzeugt.

Changelog

Version Beschreibung
8.3.0 Wenn get_class() ohne Argument aufgerufen wird, führt dies nun zu einer E_DEPRECATED-Warnung; zuvor gab diese Funktion, wenn sie innerhalb einer Klasse aufgerufen wurde, den Namen dieser Klasse zurück.
8.0.0 Der Aufruf dieser Funktion von außerhalb einer Klasse ohne jegliche Parameter löst nun einen Error aus. Zuvor wurde, wurde ein E_WARNING erzeugt und die Funktion gab false zurück.
7.2.0 Vor dieser Version war der Standardwert für object null, was denselben Effekt hatte wie das Auslassen dieses Parameters. Nun wurde null als Standardwert für object entfernt und ist keine gültige Eingabe mehr.

Beispiele

Beispiel #1 get_class()-Beispiel

<?php

class foo {
    function name()
    {
        echo "Mein Name ist " , get_class($this) , "\n";
    }
}

// create an object
$bar = new foo();

// external call
echo "Der Name ist " , get_class($bar) , "\n";

// internal call
$bar->name();

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Der Name ist foo
Mein Name ist foo

Beispiel #2 Einsatz von get_class() in einer Elternklasse

<?php

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

class foo extends bar {
}

new foo;

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #3 Verwendung von get_class() mit Klassen in Namensräumen

<?php

namespace Foo\Bar;

class Baz {
    public function __construct()
    {

    }
}

$baz = new \Foo\Bar\Baz;

var_dump(get_class($baz));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(11) "Foo\Bar\Baz"

Siehe auch

  • get_called_class() - Ermittelt den Namen der von einer statischen Methode aufgerufenen Klasse ("Late Static Binding")
  • get_parent_class() - Gibt den Namen der Elternklasse eines Objektes zurück
  • gettype() - Liefert den Datentyp einer Variablen
  • get_debug_type() - Gets the type name of a variable in a way that is suitable for debugging
  • is_subclass_of() - Prüft ob ein Objekt von der angegebenen Klasse abstammt oder sie implementiert

add a note

User Contributed Notes 37 notes

up
68
jjanak at webperfection dot net
11 years ago
>= 5.5

::class
fully qualified class name, instead of get_class

<?php
namespace my\library\mvc;

class Dispatcher {}

print Dispatcher::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher;

print $disp::class; // parse error
up
32
dave at shax dot com
12 years ago
A lot of people in other comments wanting to get the classname without the namespace. Some weird suggestions of code to do that - not what I would've written! So wanted to add my own way.

<?php
function get_class_name($classname)
{
    if ($pos = strrpos($classname, '\\')) return substr($classname, $pos + 1);
    return $pos;
}
?>

Also did some quick benchmarking, and strrpos() was the fastest too. Micro-optimisations = macro optimisations!

39.0954 ms - preg_match()
28.6305 ms - explode() + end()
20.3314 ms - strrpos()

(For reference, here's the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

<?php
c(
    function($class = 'a\b\C') {
        if (preg_match('/\\\\([\w]+)$/', $class, $matches)) return $matches[1];
        return $class;
    },
    function($class = 'a\b\C') {
        $bits = explode('\\', $class);
        return end($bits);
    },
    function($class = 'a\b\C') {
        if ($pos = strrpos($class, '\\')) return substr($class, $pos + 1);
        return $pos;
    }
);
?>
up
18
mail dot temc at gmail dot com
14 years ago
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here's a good example that should fix that for ever:

<?php

class Foo {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

class Bar extends Foo {

}

class Quux extends Bar {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

$foo = new Foo();
$bar = new Bar();
$quux = new Quux();

echo "\n--doMethod--\n";

$foo->doMethod();
$bar->doMethod();
$quux->doMethod();

echo "\n--doGetClassThis--\n";

$foo->doGetClassThis();
$bar->doGetClassThis();
$quux->doGetClassThis();

echo "\n--doGetClass--\n";

$foo->doGetClass();
$bar->doGetClass();
$quux->doGetClass();

?>

OUTPUT:

--doMethod--
Foo::doMethod
Foo::doMethod
Quux::doMethod

--doGetClassThis--
Foo::doThat
Bar::doThat
Quux::doThat

--doGetClass--
Foo::doThat
Foo::doThat
Quux::doThat
up
7
ovidiu.bute [at] gmail.com
16 years ago
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

namespace Shop;

<?php
class Foo
{
  public function __construct()
  {
     echo "Foo";
  }
}

//Different file

include('inc/Shop.class.php'); 

$test = new Shop\Foo();
echo get_class($test);//returns Shop\Foo
?>
up
2
ozana at omdesign dot cz
14 years ago
Simplest way how to gets Class without namespace

<?php
namespace a\b\c\d\e\f;

class Foo {

  public function __toString() {
    $class = explode('\\', __CLASS__);
    return end($class);
  }
}

echo new Foo(); // prints Foo
?>
up
1
andregs at NOSPAM dot gmail dot NOSPAM dot com
18 years ago
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static $_instances = array();
   protected final function __construct(){}
   
   /**
    * @param string $classname
    * @return Singleton
    */
   protected static function getInstance()
   {
      $classname = func_get_arg(0);
      if (! isset(self::$_instances[$classname]))
      {
         self::$_instances[$classname] = new $classname();
      }
      return self::$_instances[$classname];
   }
   
}

class Child extends Singleton
{
   /**
    * @return Child
    */
   public static function getInstance()
   {
      return parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
up
6
macnimble at gmail dot com
14 years ago
Need a quick way to parse the name of a class when it's namespaced? Try this:

<?php
namespace Engine;
function parse_classname ($name)
{
  return array(
    'namespace' => array_slice(explode('\\', $name), 0, -1),
    'classname' => join('', array_slice(explode('\\', $name), -1)),
  );
}
final class Kernel
{
  final public function __construct ()
  {
    echo '<pre>', print_r(parse_classname(__CLASS__),1), '</pre>';
    // Or this for a one-line method to get just the classname:
    // echo join('', array_slice(explode('\\', __CLASS__), -1));
  }
}
new Kernel();
?>

Outputs:
Array
(
    [namespace] => Array
        (
            [0] => Engine
        )

    [classname] => Kernel
)
up
1
Edward
18 years ago
The code in my previous comment was not completely correct. I think this one is. 

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }
    
    abstract protected function init();
    
    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;
        
        $class = self::getClass();
        
        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }
        
        return $instance;
    }
    
    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }
        
        return $implementing_class;
    }
}
?>
up
0
rdng1psph at relay dot firefox dot com
1 month ago
My to get the classname without the namespace:

$classPath = explode('\\', $myClass::class);
$className = array_pop($classPath);
up
1
Hayley Watson
8 years ago
Although you can call a class's static methods from an instance of the class as though they were object instance methods, it's nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

<?php
$t->Faculty();
SomeClass::Faculty(); // $t instanceof SomeClass
"SomeClass"::Faculty();
get_class($t)::Faculty();
?>

The first is legitimate, but the last makes it clear to someone reading it that Faculty() is a static method (because the name of the method certainly doesn't).
up
0
dense
9 years ago
well, if you call  get_class() on an aliased class, you will get the original class name

<?php

class Person {}

class_alias('Person', 'User');

$me = new User;

var_dump( get_class($me) ); // 'Person'

?>
up
2
luke at liveoakinteractive dot com
19 years ago
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function getclass() {
    return __CLASS__;
  }

  public function retrieve_class() {
    return get_class($this);
  }
}

class CooCoof extends BooBoof {
}

echo CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
up
0
RQuadling at GMail dot com
11 years ago
With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

<?php
namespace Foo\Bar;

abstract class Baz
{
  public function report()
  {
    echo
      '__CLASS__        ', __CLASS__, ' ', basename(__CLASS__), PHP_EOL,
      'get_called_class ', get_called_class(), ' ', basename(get_called_class()), PHP_EOL;
  }
}

class Snafu extends Baz
{
}

(new Snafu)->report();
?>

produces output of ...

__CLASS__        Foo\Bar\Baz   Baz
get_called_class Foo\Bar\Snafu Snafu
up
0
Anonymous
12 years ago
If you want the path to an file if you have i file structure like this

project -> system -> libs -> controller.php
project -> system -> modules -> foo -> foo.php

and foo() in foo.php extends controller() in controller.php like this

<?PHP
namespace system\modules\foo;

class foo extends \system\libs\controller {
    public function __construct() {
        parent::__construct();    
    }
}
?>

and you want to know the path to foo.php in controller() this may help you

<?PHP
namespace system\libs;

class controller {
    protected function __construct() {
        $this->getChildPath();
    }
    protected function getChildPath() {
        echo dirname(get_class($this));
    }
}
?>

<?PHP
$f = new foo();  // system\modules\foo
?>
up
1
Aaron
16 years ago
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
up
0
Nanhe Kumar
12 years ago
<?php
class Parent{
}
class Child extends Parent{    
}
$c = new Child();
echo get_class($c) //Child
?>
<?php
class Parent{
  public function getClass(){
     echo get_class(); 
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); //outputs Parent
?>
<?php
class Parent{
  public function getClass(){
     echo get_class($this); 
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); // Parent
?>
up
0
emmanuel dot antico at gmail dot com
13 years ago
/**
 * Obtains an object class name without namespaces
 */
function get_real_class($obj) {
    $classname = get_class($obj);

    if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
        $classname = $matches[1];
    }

    return $classname;
}
up
-2
davidsch
5 years ago
There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class  there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

e.g.

<?php
abstract class MySuperclass {
    static private $instances = array();

    static public function getInstance(): ACFBlock {
        $className = get_called_class();
        if (!isset(self::$instances[$className])) {
            self::$instances[$className] = new static();
        }
        return self::$instances[