LoginSignup
1
1

More than 5 years have passed since last update.

リフレクションで親クラスのprivate変数を取得する方法

Posted at

リフレクションで親クラスのprivate変数が取得したかったのに上手くいかなくて少しだけ調査してしまったので結果だけペタリ。

あまりいい例が思いつかなかった。

Ranko.php

class Human {
    private $realSerif = "こんにちは";
}

class Ranko extends Human {
    private $serif = "煩わしい太陽ね";

    public function hello()
    {
        echo $this->serif;
    }
}

この状態で親のprivateSerifを取ろうとしてもExceptionになる。

実行
$ranko = new Ranko();
$reflectionClass = new ReflectionClass(get_class($ranko));

echo $reflectionClass->getProperty('realSerif');

出力結果
#1 /htdocs/index.php:18
   ReflectionClass::getProperty($string1)
#2 /htdocs/index.php:18
   UNCAUGHT EXCEPTION: ReflectionException (Property realSerif does not exist)


$string1:
string(9) "realSerif"

単純に親を取得してからアクセスしてあげればよかった。

実行
$ranko = new Ranko();
$reflectionClass = new ReflectionClass(get_class($ranko));

echo $reflectionClass->getParentClass()->getProperty('realSerif');
出力結果
Property [ private $realSerif ]
array(1) {
  [0]=>
  &object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(9) "realSerif"
    ["class"]=>
    string(5) "Human"
  }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1