// ReflectionClassでプロパティをpublicにして取得する
function getProperty($object, $propertyName)
{
$reflection = new ReflectionClass($object);
$property = $reflection->getProperty($propertyName);
$property->setAccessible(true);
return $property->getValue($object);
}
// ReflectionClassでメソッドをpublicにして取得する
function getMethod($object, $methodName)
{
$reflection = new ReflectionClass($object);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method;
}
// publicではないプロパティとメソッドを持つクラス
class Foo
{
private $bar = 'BAR';
private function baz($arg)
{
return strtoupper($arg);
}
}
// インスタンス
$foo = new Foo;
// エラーになります
// Fatal error: Cannot access private property Foo::$bar ...
echo $foo->bar;
// エラーになります
// Fatal error: Call to private method Foo::baz() ...
echo $foo->baz('test');
// 'BAR'と表示されます
echo getProperty($foo, 'bar');
// 'TEST'と表示されます
echo getMethod($foo, 'baz')->invokeArgs($foo, ['test']);
September 24, 2013
ReflectionClassでpublicではないプロパティやメソッドにアクセスするメモ
ユニットテストでpublicではないメソッドのテストをする際に、結構使えたのでサンプルのソースをメモしておきます。
No comments:
Post a Comment