2012-10-26 67 views
1
abstract class foo 
{ 
    public $blah; 
} 

class bar extends foo 
{ 
    public $baz; 
} 

假設我有一個foo類從抽象bar類繼承我怎麼會得到只存在於bar但不是foo實例變量數組(即在bar級別上定義的屬性)?在上面的例子中,我想要baz但不是blah獲取實例和父實例的屬性之間的差異

+1

有反思。之前已被問過。然而,如果我可能會問,你想做什麼?從技術上講,所有的實例變量,包括繼承的變量,都存在吧 - 這就是繼承的工作原理。 *編輯:*示例如何爲類常量完成這是類似的:[在PHP中獲取常量的定義類](http://stackoverflow.com/q/11821137/367456) – hakre

回答

3

正如hakre所說,使用Reflection。搶類的父類,並且做對性能的差異,像這樣:

function get_parent_properties_diff($obj) { 
    $ref = new ReflectionClass($obj); 
    $parent = $ref->getParentClass(); 
    return array_diff($ref->getProperties(), $parent->getProperties()); 
} 

你會這樣稱呼它:

$diff = get_parent_properties_diff(new bar()); 
foreach($diff as $d) { 
    echo $d->{'name'} . ' is in class ' . $d->{'class'} . ' and not the parent class.' . "\n"; 
} 

看到它在this demo工作,其輸出:

baz is in class bar and not the parent class. 
+0

您也可以使用['ReflectionProperty :: getDeclaringClass'](http://www.php.net/manual/en/reflectionproperty.getdeclaringclass.php)來測試這個屬性。只是一個額外的說明。 – hakre

相關問題