2012-03-28 22 views

回答

9

我開始了這個快速測試。當你獲得子類的屬性時,它看起來像父類的私有屬性是隱藏的。但是,如果您調用getParentClass(),然後getProperties()您將擁有缺少的一組私人道具。

<?php 
class Ford { 
    private $model; 
    protected $foo; 
    public $bar; 
} 

class Car extends Ford { 
    private $year; 
} 

$class = new ReflectionClass('Car'); 
var_dump($class->getProperties()); // First chunk of output 
var_dump($class->getParentClass()->getProperties()); // Second chunk 

輸出(注意私人道具Ford::model丟失):

array(3) { 
    [0]=> 
    &object(ReflectionProperty)#2 (2) { 
    ["name"]=> 
    string(4) "year" 
    ["class"]=> 
    string(3) "Car" 
    } 
    [1]=> 
    &object(ReflectionProperty)#3 (2) { 
    ["name"]=> 
    string(3) "foo" 
    ["class"]=> 
    string(4) "Ford" 
    } 
    [2]=> 
    &object(ReflectionProperty)#4 (2) { 
    ["name"]=> 
    string(3) "bar" 
    ["class"]=> 
    string(4) "Ford" 
    } 
} 

第二區塊(包括福特類的所有屬性):

array(3) { 
    [0]=> 
    &object(ReflectionProperty)#3 (2) { 
    ["name"]=> 
    string(5) "model" 
    ["class"]=> 
    string(4) "Ford" 
    } 
    [1]=> 
    &object(ReflectionProperty)#2 (2) { 
    ["name"]=> 
    string(3) "foo" 
    ["class"]=> 
    string(4) "Ford" 
    } 
    [2]=> 
    &object(ReflectionProperty)#5 (2) { 
    ["name"]=> 
    string(3) "bar" 
    ["class"]=> 
    string(4) "Ford" 
    } 
} 
+0

粗糙!謝謝!我不知道你是否可以做$ class-> getParentClass() - > getProperty('model') - > setValue($ car,'F-150') – johnnietheblack 2012-03-28 19:55:02

0

我認爲你贏了」 t因爲子類不能訪問它們而獲取父私有屬性

2

儘管succ接受的答案忽略了一個有許多祖先的孩子班的可能性。這是我用來實現這一目標的實例方法:

public function getProperties() { 
    $properties = array(); 
    try { 
     $rc = new \ReflectionClass($this); 
     do { 
      $rp = array(); 
      /* @var $p \ReflectionProperty */ 
      foreach ($rc->getProperties() as $p) { 
       $p->setAccessible(true); 
       $rp[$p->getName()] = $p->getValue($this); 
      } 
      $properties = array_merge($rp, $properties); 
     } while ($rc = $rc->getParentClass()); 
    } catch (\ReflectionException $e) { } 
    return $properties; 
} 

它,直到它到達根類,而其子女的財產合併每個父母的屬性(在默認的情況下穿越了層次,僅使用在層次結構的最下部分中找到的默認值)。