在PHP中获取子类的名称 [英] Getting the name of a child class in PHP
本文介绍了在PHP中获取子类的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我正在建立一个基础类,该类将由儿童类扩展.因此,基类称为Base
,子类可以为Child1
,Child2
等.
Lets say I'm building a base class which will be extended upon by the children class. So a base class is called Base
and children can be Child1
, Child2
, etc.
在基类的构造函数中,如何获取Child1/Child2的值?
In the base class's constructor, how can i get the value of Child1/Child2?
这都是使用PHP
推荐答案
基类实际上绝对不应依赖于子类的信息---
A base class should really never depend on information about child classes---
回答您的问题:
class base {
public function __construct() {
print "Class:" . get_class($this) . "\n";
}
}
class child extends base{
public function __construct() {
parent::__construct();
}
}
$c = new child();
仅供以后参考-可以使用get_Called_class()在静态上下文中实现,但这仅在PHP> = 5.3中可用
Just for future reference -- this can be acheived in a static context using get_called_class(), but this is only available in PHP >= 5.3
这篇关于在PHP中获取子类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文