创建子类的对象时,如何从基类中获取子类的名称 [英] How to get the name of child class from base class when an object of child class is created

查看:204
本文介绍了创建子类的对象时,如何从基类中获取子类的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在基类中获取子类的名称,以便每当创建子类的对象时,我都将在基类中获取子类的名称.像这样:

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

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;

创建$object时,我希望构造函数给我创建对象的类的名称.

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

推荐答案

您可以使用get_class()向其传递当前对象引用,如下所示:

You can use get_class() passing it the current object reference, like so:

class Base_class {

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

}

您可以在PHP手册 http中找到有关get_class()的更多信息. ://php.net/manual/en/function.get-class.php

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

这篇关于创建子类的对象时,如何从基类中获取子类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆