2017-07-27 7 views
0
<?php 

class S { 
    public $a = 'a'; 
    protected $b = 'b'; 
    private $c = 'c'; 

    function get_last_child_public_properties() { 
     /* HOW TO */ 
    } 
} 

class A extends S 
{ 
    public $d = 'd'; 
    protected $e = 'e'; 
    private $f = 'f'; 
} 

class B extends A 
{ 
    public $g = 'public_g'; 
    protected $h = 'h'; 
    private $i = 'i'; 
    public $j = 'public_j'; 
} 

$b = new B(); 
$props = $b->get_last_child_public_properties(); 
/** 
* I expect $props to be equals to : 
* Array : ['g' => 'public_g', 'j' => 'public_j'] 
*/ 
+0

親の公開プロパティが必要な場合は、次のコードを使用できます: '$ reflect = new ReflectionClass(__ CLASS__);あなたの関数 'get_last_child_public_properties()'の中で$ reflect-> GetProperties(ReflectionProperty :: IS_PUBLIC);を返します。 (結果を 'var_dump'します)。それ以外の場合は、各クラスを再帰的にチェックして親クラスが存在するかどうかを確認し、パブリックプロパティを取得しない場合(最後のクラスであり、何も継承しません)、その用途はわかりません。 – ctwheels

答えて

2

PHPのRelection -classesをご覧ください。

具体的には、オブジェクト内のすべてのプロパティの配列をReflectionPropertyというインスタンスとして返します。

$classInfo= new ReflectionClass($b); 
foreach($classInfo->getProperties() as $prop) { 
    if ($prop->isPublic() && $prop->getDeclaringClass()->name == $classInfo->name) { 
     // $prop is public and is declared in class B 
     $propName = $prop->name; 
     $propValue = $prop->getValue($b); 

     // Since it is public, this will also work: 
     $propValue = $b->$propName 
     // $prop->getValue($b) will even work on protected or private properties 
    } 
} 
+0

学習に感謝します。 – user544262772

関連する問題