PHP Doku:: Ermittelt den Klassennamen eines Objekts - function.get-class.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenKlassen- und ObjektinformationenKlassen- und Objekt-Funktionenget_class

Ein Service von Reinhard Neidl - Webprogrammierung.

Klassen- und Objekt-Funktionen

<<get_class_vars

get_declared_classes>>

get_class

(PHP 4, PHP 5)

get_classErmittelt den Klassennamen eines Objekts

Beschreibung

string get_class ([ object $object ] )

Ermittelt den Klassennamen für das bergebene object.

Parameter-Liste

object

Das gewünschte Objekt

Rückgabewerte

Liefert den Namen der Klasse deren Instanz object ist. Ist object kein Objekt so wird FALSE zurückgegeben.

Changelog

Version Beschreibung
Ab 5.0.0 Der Klassenname wird in seiner Orginalform inclusive Groß- und Kleinschreibung zurückgegeben.
Ab 5.0.0 Der Parameter object ist optional wenn die Funktion aus einer Methode einer Klasse aufgerufen wird. Ohne Parameter wird in diesem Fall der Name der Klasse zurückgegeben zu der die Methode gehört.

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"

Siehe auch


39 BenutzerBeiträge:
- Beiträge aktualisieren...
me at nwhiting dot com
6.12.2010 17:14
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
 * Returns the name of a class using get_class with the namespaces stripped.
 * This will not work inside a class scope as get_class() a workaround for
 * that is using get_class_name(get_class());
 *
 * @param  object|string  $object  Object or Class Name to retrieve name

 * @return  string  Name of class with namespaces stripped
 */
function get_class_name($object = null)
{
    if (!
is_object($object) && !is_string($object)) {
        return
false;
    }
   
   
$class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return
$class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class
TestClass {
   
    public function
test()
    {
       return
get_class_name(get_class());
    }
}

class
GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function
testGetClassName()
    {
       
$class  = new TestClass();
       
$std  = new \stdClass();
       
$this->assertEquals('TestClass', get_class_name($class));
       
$this->assertEquals('stdClass', get_class_name($std));
       
$this->assertEquals('Test', get_class_name('Test'));
       
$this->assertFalse(get_class_name(null));
       
$this->assertFalse(get_class_name(array()));
       
$this->assertEquals('TestClass', $class->test());
    }
}
?>
Aaron
18.06.2010 20:14
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.
ovidiu.bute [at] gmail.com
6.04.2010 7:23
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
?>
Tom Brown
17.09.2009 20:02
As of 5.3.0 this function seems to have started throwing an E_WARNING error if you pass it a non-object. Supress that with "@" if you are actually checking and handling the false return code.
Lanselot
11.02.2009 11:09
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class A {
    function
foo() {
      return
get_class();
    }
}
class
B extends A {
   function
bar() {
      return
get_class();
   }
}
$instance = new B();
echo
$instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
danbettles at yahoo dot co dot uk
8.10.2008 20:56
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function
__construct() {
    }

    final public static function
getInstance() {
        static
$aoInstance = array();

       
$calledClassName = get_called_class();

        if (! isset (
$aoInstance[$calledClassName])) {
           
$aoInstance[$calledClassName] = new $calledClassName();
        }

        return
$aoInstance[$calledClassName];
    }

    final private function
__clone() {
    }
}

class
DatabaseConnection extends Singleton {

    protected
$connection;

    protected function
__construct() {
       
// @todo Connect to the database
   
}

    public function
__destruct() {
       
// @todo Drop the connection to the database
   
}
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Maik
4.10.2008 17:36
The code just worked fine with PHP 5.3.
Thanks to you it could be rebuild to work with earlier versions of PHP 5.

I just changed the 'static' to 'self' and die() to an Exception.

<?php
// This one extends Singleton with proper class name
class someSingleton extends Singleton {
    public static function
getInstance() {
       
parent::$__CLASS__ = __CLASS__;
       
parent::getInstance();
    }
}
// This one does the logic
abstract class Singleton {
    protected static
$__CLASS__ = __CLASS__;
    protected static
$instance = null;

    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() {      
       
$class = self::getClass();
      
        if (
self::$instance === null) {
           
self::$instance = new $class();
           
self::$instance->init();
        }
      
        return
self::$instance;
    }
  
   
/**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
   
private static function getClass() {
       
$implementing_class = self::$__CLASS__;
       
$original_class = __CLASS__;

        if (
$implementing_class === $original_class)
            throw new
Exception("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
      
        return
$implementing_class;
    }
}
?>
Edward
21.08.2008 12:26
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;
    }
}
?>
Edward
20.08.2008 14:42
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static
$__CLASS__ = __CLASS__;
    protected static
$instance;
   
    protected function
__construct() {
        static::
$instance = $this;
       
$this->init();
    }
   
    abstract protected function
init();
   
    protected function
getInstance() {
       
$class = static::getClass();
       
        if (static::
$instance===null) {
            static::
$instance = new $class;
        }

        return static::
$instance;
    }
   
    private static function
getClass() {
        if (static::
$__CLASS__ == __CLASS__) {
            die(
"You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }
       
        return static::
$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static
$__CLASS__ = __CLASS__; // Provide this in each singleton class.

   
protected function someFunction() {
       
$instance = static::getInstance();
       
// ...
   
}
}
?>

Hope this helps you save some time :)
James
22.06.2008 11:46
To get round this problem, another option is a factory to create singletons.

<?php
class Factory {
  private static
$instances = array();
  public static function
getInstance($class_name) {
    if(!
array_key_exists($class_name, self::$instances)) {
     
self::$instances[$class_name] = new $class_name();
    }
    return
self::$instances[$class_name];
  }
}
?>

I guess you could modify this to create singletons from some, and prototypes for the rest.

There's probably some good way to stop people instantiating objects directly. Perhaps by using the backtrace in the constructor of the class to ensure that it was indeed the Factory that created the object.
Anonymous
30.04.2008 6:59
I jumped the gun. The following code also working for statics called inside other classes.

<?php
       
for( $i=0 ; $i < count($bt) ; $i++)
        {
            if(
$bt[$i]['function'] == 'getInstance')
            {
               
$class = $bt[$i]['class'];
               
            } else {
                break;
            }
        }
?>
dave dot zap at gmail dot com
30.04.2008 6:13
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php
$bt
= debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-1 ; $i > 0 ; $i--)
{
    if(
$bt[$i]['function'] == 'getInstance')
    {
       
$class = $bt[$i]['class'];
        break;
    }
}
?>
Anonymous
12.04.2008 23:01
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
frederic dot sureau at gmail dot com
29.02.2008 20:01
@ hek :

The problem is that the method getInstance() in a Singleton must be static, so we cannot use $this because it doesn't exists :(
andregs at NOSPAM dot gmail dot NOSPAM dot com
21.02.2008 22:17
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".
hek at theeks dot net
10.01.2008 21:51
I may be missing something, but in all the laments wishing for some sort of get_real_class() function to return the final class name of of a derived class (a.k.a. subclass), my testing suggests that the existing get_class() function can do this just fine, at least when an object of the derived class has been instantiated.

Consider:

<?php

class BaseClass {
  function
whoAmI() {
    return
get_class($this);
  }
}

class
DerivedClass extends BaseClass {}

$baseInstance = new BaseClass();
$derivedInstance = new DerivedClass();

echo
$baseInstance->whoAmI(); // returns "BaseClass"
echo $derivedInstance->whoAmI(); // returns "DerivedClass"
echo BaseClass::whoAmI(); // returns an empty string
echo DerivedClass::whoAmI(); // returns an empty string

?>

In my opinion, the final two calls in my example should actually throw runtime errors, but apparently they don't.

Now consider:

<?php

class BaseClass {
  function
whoAmI() {
    return
get_class(/* $this */);
  }
}

class
DerivedClass extends BaseClass {}

$baseInstance = new BaseClass();
$derivedInstance = new DerivedClass();

echo
$baseInstance->whoAmI(); // returns "BaseClass"
echo $derivedInstance->whoAmI(); // returns "BaseClass"
echo BaseClass::whoAmI(); // returns "BaseClass"
echo DerivedClass::whoAmI(); // returns "BaseClass"

?>

So you can see, if you need to know the final class name of an *object* constructed from a subclass there's no problem, though if what you're after is the final class name of a derived class *for which you have no instance handy* then what I've demonstrated here isn't going to help you with that -- though it's hard for me to imagine you could write code like DerivedClass::whoAmI() and seriously care about the value you get back, since this line of code itself shows that you know the final class name of the derived class already to begin with!  But people are clever, so maybe there is some case where my simple view on this breaks down.  Anyway, happy trails.  I hope this helps someone someday.
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk
9.09.2007 14:40
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected
$m_instanceName = '';
   
    public static function
classDisplayName()
    {
        return
'Base Class';
    }
   
    public function
instanceDisplayName()
    {
       
//here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
       
return $this->m_instanceName . ' - ' . self::classDisplayName();
    }
}

class
Derived extends Base
{
    public function
Derived( $name )
    {
       
$this->m_instanceName = $name;
    }
   
    public static function
classDisplayName()
    {
        return
'Derived Class';
    }
}

$o = new Derived('My Instance');
echo
$o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected
$m_instanceName = '';
   
    public static function
classDisplayName()
    {
        return
'Base Class';
    }
   
    public function
instanceDisplayName()
    {
       
$realClass = get_class($this);
        return
$this->m_instanceName . ' - ' . call_user_func(array($realClass, 'classDisplayName'));
    }
}

class
Derived extends Base
{
    public function
Derived( $name )
    {
       
$this->m_instanceName = $name;
    }
   
    public static function
classDisplayName()
    {
        return
'Derived Class';
    }
}

$o = new Derived('My Instance');
echo
$o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us
20.08.2007 17:40
@ Frederik :

<?
$class
= $bt[count($bt) - 1]['class'];
?>

should be

<?
$class
= $bt[count($bt) - 2]['class'];
?>

;-)
Frederik Krautwald
25.06.2007 17:13
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static
$_instances = array();
  
    protected function
__construct() {}
  
    protected static function
getInstance() {
       
$bt = debug_backtrace();
       
$class = $bt[count($bt) - 1]['class'];
        if (!isset(
self::$_instances[$class])) {
           
self::$_instances[$class] = new $class();
        }
        return
self::$_instances[$class];
    }
}
class
A extends Singleton {
    public static function
getInstance() {
        return
parent::getInstance();
    }
}
class
B extends Singleton {
    public static function
getInstance() {
        return
parent::getInstance();
    }
}
class
C extends A {
    public static function
getInstance() {
        return
parent::getInstance();
    }
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo
"\$a is a " . get_class($a) . "<br />";
echo
"\$b is a " . get_class($b) . "<br />";
echo
"\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com
23.06.2007 15:20
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static
$instances = array();
   
    protected
__construct(){}
   
    protected function
getInstance() {
       
$class = get_real_class(); // imaginary function returning the final class name, not the class the code executes from
       
if (!isset(self::$instances[$class])) {
           
self::$instances[$class] = new $class();
        }
        return
self::$instances[$class];
    }
}
class
A extends Singleton {
}
class
B extends Singleton {
}

$a = A::getInstance();
$b = B::getInstance();

echo
"\$a is a " . get_class($a) . "<br />";
echo
"\$b is a " . get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static
$instances = array();
   
    protected
getInstance($class) {
        if (!isset(
self::$instances[$class])) {
           
self::$instances[$class] = new $class();
        }
        return
self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
Bryan
19.06.2007 17:07
janci's Singleton example is all well and good, until you create another class "Bar" which also extends Singleton.

<?php
$single_foo
= Foo::getInstance();
$single_bar = Bar::getInstance();
?>

$single_bar will now be an instance of Foo! This is because there is only one copy of the static variable $__instance in the Singleton class. Here is a better Singleton class:

<?php
abstract class Singleton {
    static
$_instances = array();

   
//Prevent singletons from being instantiated other than via getInstance();
   
protected function __construct() {}
    protected function
__clone() {}
      
    static function
getInstance($class_name) {
        if(!isset(
self::$_instances[$class_name])) {
           
self::$_instances[$class_name] = new $class_name();
        }
        return
self::$_instances[$class_name];
    }
}
?>

Unfortunately, you are still required to define Foo as janci does. I would love to see an example where the only thing you add to the class is "extends Singleton" and you're done, but that seems to be impossible.
janci
30.04.2007 21:00
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern.

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static
$__instance = false;
       
    public static function
getInstance()
    {   
        if (
self::$__instance == false)
        {
           
// This acctually is not what we want, $class will always be 'Singleton' :(
           
$class = get_class();
           
self::$__instance = new $class();           
        }
        return
self::$__instance;
    }
}

class
Foo extends Singleton
{
   
// ...
}

$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static
$__instance = false;
       
    protected static function
getInstance($class)
    {   
        if (
self::$__instance == false)
        {
            if (
class_exists($class))
            {
               
self::$__instance = new $class();           
            }
            else
            {
                throw new
Exception('Cannot instantiate undefined class [' . $class . ']', 1);
            }
        }
        return
self::$__instance;
    }
}

class
Foo extends Singleton
{
   
// You have to overload the getInstance method in each extended class:
   
public static function getInstance()
    {
        return
parent::getInstance(get_class());
    }
}

$single_foo = Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
yicheng zero-four at gmail dot com
27.04.2007 21:29
To matsgefvert dot se and Marc,

I'm sorry but I'm still having a very difficult time understanding why you would want this behavior.  I understand that you are generating some code for some persistent layer for database access. 

In your code example, Marc, you say that you would like the SomeTable::read() to return "SomeTable" when called from your client.  Yet, at this point you *know* what the class name is.  Even assuming you are generating this code automatically, you can simply generate your SomeTable class as such.

<?php

class PersistedObject {
 
//...
 
public static function read($table, $key){
   
// do some databasey stuff
    // with $table which is the table name
   
return $table;
  }
}

class
SomeTable extends PersistedObject {
 
//...
  // make a copy in the child class
 
public static function read($key){
   
$table = get_class();
    return
parent::read($table, $key);
  }
}

// this will now return "SomeTable"
$someTableObject = SomeTable::read(1234);

?>

I'm still failing to see how this would provide but a convenience for very rare & specific issues, at the cost of non-OOP behavior by allowing static methods to bind to objects instead of classes. 

One of the most common uses for get_class() is for debugging lines, for example:

<?php

class PersistedObject {
 
//...
 
public static function transaction($params){
   
// do some stuff
   
if ($error_occurred){
      echo
"Error : WTFBBQ happened in " . get_class() . "::" . __FUNCTION__ . ".  Time to get some coffee!";
  }
}

class
SomeTable extends PersistedObject {
 
//...
}

SomeTable::transaction( $someParams );
?>

Now, when an error occurs inside the call to SomeTable::transaction(), we get incorrect error output.
Kerry Kobashi
15.04.2007 8:58
It should be noted that class names are represented in lowercase under PHP 4.x.

class MyClass {
   function MyClass() {
   }
   function ShowClass() {
      echo get_class($this);
   }
}

$p = new MyClass();
$p->ShowClass();

Displays:

myclass

If you serialize $p, you will also see that the class name is lower case as well:

$p = new MyClass();
echo serialize($p);

Displays:

O:7:"myclass":1:{s:3:"val";i:100;}

In my case, this is an important point for mapping class names to database table names (and vice versa).
Marc W.
13.04.2007 18:40
The previous comment (from matsgefvert dot se) is 100% correct. To further elaborate on the persistence layers example suggested, consider the case where you are dynamically creating inherited objects. For example:
<?php

class PersistedObject {
//...
public static function read($key){
//You will need the table name here to actually read
// from the persistence medium
echo get_class();
}

class
SomeTable extends PersistedObject {
//...
}

/*
Somewhere else in our code we would like to call the read method
*/

$someTableObject = SomeTable::read(1234);

?>
Remember that the SomeTable class would be generated on the fly, probably by some DB schema. The problem is that you would actually like the above example to output "SomeTable", but unfortunately, it will output "PersistedObject".
spam at matsgefvert dot se
24.02.2007 10:37
I disagree with the notion that the authors of the previous posts are unfamiliar with OOP. Without the ability to know from general (parent) objects what kind of classes we're operating on, it makes things rather difficult, especially in building frameworks that rely heavily on class types (e.g. persistence layers).

The proposed BooBoof::getclass() and CooCoof::getclass() scheme will not work in some particular scenarios since static calls aren't virtual, which means a parent class will always call its own getclass() function instead of the one needed to find out the class name.

The only solution I've found is to pass along a string containing the class name we're working on to the generalized functions. It is however an ugly solution, certainly less than ideal and goes against what OOP and reflection is all about, IMHO.
yicheng zero-four at gmail dot com
18.01.2007 21:22
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
makc dot the dot great at gmail dot com
17.12.2006 18:29
Check it out:

<?php

class A {
 function
s () { return "A::s"; }
 function
s1 () { return $this->s(); }
}

class
B extends A {
 function
s () { return "B::s"; }
}

$a = new A(); echo $a->s1();
echo
"<br>";
$b = new B(); echo $b->s1();
echo
"<br>";

class
C {
 static function
s () { return "C::s"; }
 static function
s1 () { return self::s(); }
}

class
D extends C {
 static function
s () { return "D::s"; }
}

echo
C::s1();
echo
"<br>";
echo
D::s1();
echo
"<br>";

?>

Output:
A::s
B::s
C::s
C::s

Seems like static function always belong to its class.
luke at liveoakinteractive dot com
6.12.2006 16:03
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.
benjaminhill at gmail dot com
27.04.2006 19:47
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
brjann at NOSPAMATALLgmail dot com
16.11.2005 21:39
This behavior is unexpected, but good to be aware of

class parentclass {
    public function getClass(){
        echo get_class($this); //using "$this"
    }
}
class child extends parentclass {
}

$obj = new child();
$obj->getClass(); //outputs "child"

class parentclass {
    public function getClass(){
        echo get_class(); //note, no "$this"
    }
}
class child extends parentclass {
}

$obj = new child();
$obj->getClass(); //outputs "parentclass"
davidc at php dot net
13.10.2005 19:25
As of php5, you cannot use get_class($this); in a public static function. You would have to do something like this:

<?php

class BooBoof {
    public static function
getclass()
    {
        return
__CLASS__;
    }
}

$c = BooBoof::getclass();
print
$c;
?>

To get the class since you cannot use
<?php
public static function getclass()
{
    return
get_class($this);
}
?>

Rather simple and straightforward but that might help some people that are searching for it..
wired at evd dot ru
25.09.2005 11:25
There is one unexpected bahaviour (for me as least):

<?php

 
class parent
 
{
    ...

    public function
getInstance ($id)
    {
      ...

      print
get_class() . "\n" . __CLASS__;

      ...
    }
  }

  class
child extends parent
 
{
    ...
  }

 
child::getInstance(...);
?>

This code will produce:

  parent
  parent

So I can't make "new $className(...)" in getInstance(). The only option is to do a fabric.
kunxin at creaion dot com
25.07.2005 14:30
I just migrated from PHP 4 to PHP 5 and noticed that in PHP 5.03 that a lot of code dependent on get_class() and its variants stop working.

It turns out that get_class() and its variants are now case-sensitive.
refrozen dot com
6.07.2005 0:01
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
MagicalTux at FF.ST
2.02.2004 13:11
Note that the constant __CLASS__ is different from get_class($this) :
<?
 
class test {
    function
whoami() {
      echo
"Hello, I'm whoami 1 !\r\n";
      echo
"Value of __CLASS__ : ".__CLASS__."\r\n";
      echo
"Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class
test2 extends test {
    function
whoami2() {
      echo
"Hello, I'm whoami 2 !\r\n";
      echo
"Value of __CLASS__ : ".__CLASS__."\r\n";
      echo
"Value of get_class() : ".get_class($this)."\r\n\r\n";
     
parent::whoami(); // call parent whoami() function
   
}
  }
 
$test=new test;
 
$test->whoami();
 
$test2=new test2;
 
$test2->whoami();
 
$test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.
Dan
30.01.2003 7:00
This function does return the class name in lowercase, but that does not seem to make any difference. The code below, although very sloppy, works fine in all of the following configurations.

PHP 4.2.2 on Windows NT5 with Apache 1.3.24
PHP 4.2.1 in Zend Development Environment on box above
PHP 4.2.3 on Linux RedHat 7.3 with Apache 1.3.27

class TeSt {
   var $a;
   var $b = "Fred";

   // Notice the case difference in the constructor name

   function Test() {
      $classname = get_class($this); // $classname = "test"
      $this->ra = get_class_vars($classname);
   }
}
// Next line also works with Test(), TEST(), or test()
$obj = new TeSt();
print_r($obj->ra);

Result :
   Array
   (
       [a] =>
       [b] => Fred
   )
oliver DOT pliquett @mediagear DOT de
13.08.2002 17:07
This function can become _VERY_ helpful if you want to return a new object of the same type. See this example:

<?php
class Foo{
    var
$name;
   
    function
Foo( $parameter ){
       
$this->name = $parameter;
    }

    function
whoami() {
        echo
"I'm a " . get_class( $this ) ."\n";
    }
   
    function
getNew() {
       
$className = get_class( $this );
       
       
// here it happens:
       
return new $className ( "world" ) ;
    }
}
class
Bar extends Foo {

    function
Bar( $name ){
       
$this->Foo( $name );
    }

    function
welcome() {
        echo
"Hello, " . $this->name "! \n";
    }
}

// We generate a Bar object:
$myBar = new Bar( "Oliver" );
$myBar->welcome();

//now let's instanciate a new Bar object.
//note: this method is inherited from Foo by Bar!

$baba = $myBar->getNew();

$baba->welcome();
$baba->whoami();

/* Output:
Hello, Oliver!
Hello, world!
I'm a bar
*/
?>
philip at cornado dot com
20.06.2002 21:15
As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)