Getting the name of a child class in the parent class (static context)

前端 未结 9 921
栀梦
栀梦 2020-11-29 20:19

I\'m building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code bel

9条回答
  •  無奈伤痛
    2020-11-29 20:52

    You don't need to wait for PHP 5.3 if you're able to conceive of a way to do this outside of a static context. In php 5.2.9, in a non-static method of the parent class, you can do:

    get_class($this);
    

    and it will return the name of the child class as a string.

    i.e.

    class Parent() {
        function __construct() {
            echo 'Parent class: ' . get_class() . "\n" . 'Child class: ' . get_class($this);
        }
    }
    
    class Child() {
        function __construct() {
            parent::construct();
        }
    }
    
    $x = new Child();
    

    this will output:

    Parent class: Parent
    Child class: Child
    

    sweet huh?

提交回复
热议问题