The wood has the title to say so simple!!
The problem is:
Class A in PHP Inherits Class B, and how to get classes name of Class B in Class A
The actual conditions of use are:
Class B is a base class, multiple classes a,c,d ..... Need to inherit class B. I want to write some logs in class B to record the operation of Class A.
Reply content:
The wood has the title to say so simple!!
The problem is:
Class A in PHP Inherits Class B, and how to get classes name of Class B in Class A
The actual conditions of use are:
Class B is a base class, multiple classes a,c,d ..... Need to inherit class B. I want to write some logs in class B to record the operation of Class A.
My way is relatively simple, in the class B to define a property, B in the constructor of the __class__ assignment to this property, the subclass call this property to know the class name of B.
Code:
Class b{
protected $name = ''; public function __construct(){ $this->name = __CLASS__; }}class A extends B{ public function _show(){ echo $this->name; }}$temp = new A();$temp->_show();
Defining a function is just fine.
Base classes and subclasses can be called from one another.
You write a function in Class B (Word Class):
private function getChildName(){ return __CLASS__;}
You can call it in Class A (base class):
$this->getChildName();
Multiple inheritance to get the parent class name in the subclass 1. Use reflection 2. Use callbacks (including child-parent calls) 3. Define the Self-class method in the parent class.
The landlord raised the question seems to be:
Because A,c,d are inherited B, the functions in B need to be "A, or c" "?
class Base { public function log() { // 目标类,输出:A、C echo static::class; //echo get_called_class(); //echo get_class($this); // 基类,输出:Base //echo __CLASS__; //echo self::class; }}class A extends Base {}class C extends Base {}echo (new A)->log(); // 输出: Aecho (new C)->log(); // 输出: C
If your needs are in a, know who inherits, this can be used to reflect the
// 类外获得$a = new A();echo get_parent_class($a);//类中获得class C extends Base { public function log1() { echo get_parent_class($this); }}// 反射,取出所有extends的父级// 如上,在C类中,$a换成$this即可$class = new ReflectionClass($a);$parents = [];while ($class = $class->getParentClass()) { // 查询 implements 用 getInterfaces $parents[] = $class->getName();}print_r($parents);
> more information, see for yourself
Debugging
Reflection
Function
Get_called_class
Get_class
Get_class_methods
Get_class_vars
Get_object_vars
Get_parent_class
Method_exists