>= 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(PHP 4, PHP 5, PHP 7, PHP 8)
get_class — Ermittelt den Klassennamen eines Objekts
Ermittelt den Klassennamen für das übergebene object.
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.
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.
| 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.
|
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"
>= 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 errorA 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;
}
);
?>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::doThatIf 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
?>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
?>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".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
)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;
}
}
?>My to get the classname without the namespace:
$classPath = explode('\\', $myClass::class);
$className = array_pop($classPath);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).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'
?>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.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 SnafuIf 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
?>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.<?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
?>/**
* 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;
}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[