2011-11-26 59 views
13

类我有OOP PHP代码:获取父扩展在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()会从我的B类返回a

我怎样才能获得(从我的代码)类a

感谢

+4

阅读此:http://stackoverflow.com/questions/506705/php-get-classname-from-static-call-in-extended-class –

回答

16

您的代码建议您使用parent,这实际上就是您需要的。问题在于魔术__CLASS__变量。

documentation状态:

由于PHP 5本常量返回类的名字,因为它被宣布的。

这是我们所需要的,但作为this comment注意到php.net:

克劳德指出,__CLASS__总是包含类,这就是所谓的,如果你宁愿有类调用方法使用get_class($ this)来代替。但是,这只适用于实例,不适用于静态调用。

如果你只需要父类,那么它也是一个函数。这一个被称为get_parent_class

15

您可以使用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)代替。

10

您可以使用反射来做到这一点:

使用class_parents,而不是相反的

parent::__CLASS__; 

使用

$ref = new ReflectionClass($this); 
echo $ref->getParentClass()->getName(); 
11
class a { 
    // with propertie and functions 
} 

class b extends a { 

    public function test() { 
     echo get_parent_class($this); 
    } 
} 


$b = new b(); 
$b->test(); 
6

。它会给一群父母。

<?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