tags:

views:

81

answers:

4
class Bob extends Person
{
    //do some stuff
}

class Person
{
    public function __construct()
    {
        //get the class name of the class that is extending this one
        //should be Bob
    }
}

How can I get the class name of Bob from inside the constructor of the Person class?

+1  A: 
<?php

class Bob extends Person
{

    public function __construct()
    {
     parent::__construct();
    }

    public function whoAmI()
    {
     echo "Hi! I'm ".__CLASS__.", and my parent is named " , get_parent_class($this) , ".\n";
    }
}

class Person
{
    public function __construct()
    {
     echo "Hello. My name is ".__CLASS__.", and I have a child named " , get_class($this) , ".\n";
    }
}

// Hello. My name is Person, and I have a child named Bob.
$b = new Bob;
// Hi! I'm Bob, and my parent is named Person.
$b->whoAmI();
simeonwillbanks
Same here - he wanted the child class.
Franz
This code is now correct since it has been edited.
Kevin
In my haste, I placed the main logic in the wrong location. I'm going to use my __CLASS__ constant idea to do one more edit.
simeonwillbanks
+6  A: 

Use get_class($this).

It works for sub-class, sub-sub-class, the parent class, everything. Just try it! ;)

Savageman
+3  A: 
class Person
{
  public function __construct()
  {
    echo get_class($this);
  }
}

class Bob extends Person
{
  //do some stuff
}

$b = new Bob;

prints Bob as explained in "Example #2 Using get_class() in superclass" at http://docs.php.net/get_class

VolkerK
+2  A: 
class Bob extends Person
{
    //do some stuff
}

class Person
{
    public function __construct()
    {
     var_dump(get_class($this)); // Bob
        var_dump(get_class());   // Person
    }
}

new Bob;

Source: http://www.php.net/manual/en/function.get-class.php

Dor