2011-11-26 58 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