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 mediumecho 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".

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;

<?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

Use get_class() to get the name of class ,it will help you get the class name, in case you extend that class with another class and want to get the name of the class to which object is instance of user get_class($object)

when you create an object of class{$b object of B} which has a super class{Class A}. uses these code IN Super Class {A} --------------------------------------------to get class name B{object instance} : get_class($this) to get class name A{super class} : get_class() or get_parent_class($this)

Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available. Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

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:

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:<?phpabstract 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:<?phpabstract class Singleton{ protected static $__instance = false;

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 ;)

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:

<?phpclass 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 classreturn $this->m_instanceName . ' - ' . self::classDisplayName(); }}

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:

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.

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.

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.

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.

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.

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.

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.

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.

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.

/**
* 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();

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'];

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.