[英]get parent extends class in php
我有oop php代码:
class a {
// with properties and functions
}
class b extends a {
public function test() {
echo __CLASS__; // this is b
// parent::__CLASS__ // error
}
}
$b = new b();
$b->test();
我有一些父类(普通和抽象)和许多子类。 子类扩展了父类。 因此,当我在某个时候实例化孩子时,我需要找出我叫什么父母。
例如,函数b::test()
将返回a
我怎样才能获得(从我的代码)类a
从我的b类?
谢谢
您的代码建议您使用parent ,这实际上是您所需要的。 问题在于神奇的__CLASS__
变量。
该文档指出:
从PHP 5开始,此常量返回声明的类名称。
这就是我们所需要的,但是正如在php.net上的注释中所指出的:
claude指出
__CLASS__
始终包含被调用的类,如果您希望让调用该方法的类使用get_class($ this)代替。 但是,这仅适用于实例,不适用于静态调用。
如果只需要父类,那么还有一个函数。 那个叫get_parent_class
您可以使用get_parent_class
:
class A {}
class B extends A {
public function test() {
echo get_parent_class();
}
}
$b = new B;
$b->test(); // A
如果B::test
是静态的,这也将起作用。
注意:使用不带参数的get_parent_class
与将$this
作为参数传递之间存在细微的差别。 如果将上述示例扩展为:
class C extends B {}
$c = new C;
$c->test(); // A
我们将A
作为父类(B的父类,在其中调用该方法)。 如果您始终想要您要测试的对象的最接近的父对象,则应改用get_parent_class($this)
。
class a {
// with propertie and functions
}
class b extends a {
public function test() {
echo get_parent_class($this);
}
}
$b = new b();
$b->test();
您可以使用反射来做到这一点:
代替
parent::__CLASS__;
使用
$ref = new ReflectionClass($this);
echo $ref->getParentClass()->getName();
请改用class_parents
。 它会给很多父母。
<?php
class A {}
class B extends A {
}
class C extends B {
public function test() {
echo implode(class_parents(__CLASS__),' -> ');
}
}
$c = new C;
$c->test(); // B -> A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.