How to get the name of a child class from a base class when creating a child class object

I want to get the name of my child class in the base class so that whenever a child class object is created, I get the name of the child class in the base class. Something like that:

class Base_class {
    function __construct() {
        // Some code Here to get the name of the child class
    }
}

class Child_class extends Base_Class {}

class Another_child_class extends Base_Class {}

$object = new Child_Class;
$object2 = new Another_child_class;

When created $object, I want the constructor to give me the name of the class from which the object was created.

+4
source share
4 answers

You can use get_class()by passing it the current link to the object, for example:

class Base_class {

    function __construct() {
        $calledClassName = get_class($this);
    }

}

Edit: You can find more information get_class()in the PHP manual http://php.net/manual/en/function.get-class.php

+1
source

, - . PHP 5.5 ​​ ::class, , . parent, self static. :

<?php

class A {}

class B extends A
{
    public function foo() {
        echo parent::class . "\n";    // A
        echo __CLASS__ . "\n";        // B
        echo self::class . "\n";      // B
        echo static::class . "\n";    // D
        echo get_class($this) . "\n"; // D
    }
}

class C extends B {}
class D extends C {}

(new D)->foo();

self::class , __CLASS__, , ( B).

parent::class (A).

static::class, Late Static Binding, , (D).

, , (C) ( debug_backtrace ).

+7

This is possible by using static::class(or get_class($this)or get_called_class()) in the base class to get the name of the child (which is initially called at run time):

<?php

class Foo 
{

    public function __construct()
    {
        var_dump(static::class, get_class($this), get_called_class());
    }

}

class Bar extends Foo { }

class Baz extends Bar { }

new Foo();
new Bar();
new Baz();

It produces:

string(3) "Foo"
string(3) "Foo"
string(3) "Foo"
string(3) "Bar"
string(3) "Bar"
string(3) "Bar"
string(3) "Baz"
string(3) "Baz"
string(3) "Baz"

This is called late static binding . Here is a demo above.

+4
source

Well, just pass this explicitly:

class BaseClass{

  function __construct($tableName){
    // do stuff w/ $tableName
  }

}

class ChildClass extends BaseClass{

  function __construct(){
    parent::__construct('ChildClass');
  }

}
0
source

All Articles