Andrew
Andrew

Reputation: 238717

PHP: Is it possible to retrieve the class name of a child class?

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?

Upvotes: 1

Views: 248

Answers (4)

simeonwillbanks
simeonwillbanks

Reputation: 1459

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

Upvotes: 1

Dor
Dor

Reputation: 7494

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

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

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

Upvotes: 3

Savageman
Savageman

Reputation: 9487

Use get_class($this).

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

Upvotes: 7

Related Questions