Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class name of the constructing class [duplicate]

Tags:

php

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.

like image 660
JvdBerg Avatar asked Oct 03 '12 08:10

JvdBerg


People also ask

What is duplicate class in Java?

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.

What is the error duplicate class?

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.


2 Answers

public function __construct() {
    $this->name = get_class($this);
}

http://php.net/get_class

like image 159
deceze Avatar answered Oct 12 '22 02:10

deceze


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.

like image 3
lonesomeday Avatar answered Oct 12 '22 03:10

lonesomeday