Possible Duplicate:
Get class name from extended class
Suppose I have the following:
class Foo
{
public $name;
public __construct()
{
$this->name = __CLASS__;
}
}
class Bar extends Foo
{
}
class FooBar extends Foo
{
}
$bar = new Bar();
echo $bar->name; // will output 'Foo', but I want 'Bar'
$foobar = new FooBar();
echo $foobar->name; // will output 'Foo', but I want 'FooBar'
Is there a way to get the name of the constructing class, without setting the name in a extended class e.g. setting the name in class Foo?
Note: I have a lot of classed derived from Foo, setting the name in every derived class would be a lot of coding.
The "duplicate class" error can also occur when the class is named the same with the same package naming hierarchy, even if one of the classes exists in a directory structure with directory names different than the package names. This is shown in the next screen snapshot.
This may be due to an unsuccessfull name change of the module. In such a case, the module is copied in the javasource folder in the app directory with a new name and the old folder is kept, resulting in two identical folders with different names.
public function __construct() {
$this->name = get_class($this);
}
http://php.net/get_class
This is very easy: just use get_called_class
:
$this->name = get_called_class();
This is part of the late static binding features introduced in PHP 5.3. It refers to the class called, rather than the class where the method is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With