PHPリフレクション

Nette\Utils\Reflection は、PHPリフレクションのための便利な関数を持つ静的クラスです。その目的は、ネイティブクラスの欠点を修正し、異なるPHPバージョン間で動作を統一することです。

インストール:

composer require nette/utils

すべての例は、エイリアスが作成されていることを前提としています:

use Nette\Utils\Reflection;

areCommentsAvailable(): bool

リフレクションがPHPDocコメントにアクセスできるかどうかを調べます。コメントはオペコードキャッシュのために利用できない場合があります。例えば、opcache.save-comments ディレクティブを参照してください。

expandClassName (string $name, ReflectionClass $context)string

クラス名 $name をクラス $context のコンテキストで、つまりその名前空間と定義されたエイリアスのコンテキストで完全な名前に展開します。つまり、PHPパーサーがクラス $context の本体に書かれていた場合に $name をどのように理解するかを示します。

namespace Foo;
use Bar;

class DemoClass
{
	// new Bar, new Baz
}

$context = new ReflectionClass(Foo\DemoClass::class);
Reflection::expandClassName('Bar', $context); // 'Bar'
Reflection::expandClassName('Baz', $context); // 'Foo\Baz'

getMethodDeclaringMethod (ReflectionMethod $method): ReflectionMethod

メソッド $method の宣言を含むメソッドのリフレクションを返します。通常、各メソッドは自身の宣言ですが、メソッドの本体はトレイト内にあり、異なる名前で存在することもあります。

PHPは実際の宣言を特定するための十分な情報を提供しないため、Netteは信頼できるはずの独自のヒューリスティックを使用します。

trait DemoTrait
{
	function foo()
	{
	}
}


class DemoClass
{
	use DemoTrait {
		DemoTrait::foo as foo2;
	}
}


$method = new ReflectionMethod('DemoClass::foo2');
Reflection::getMethodDeclaringMethod($method); // ReflectionMethod('DemoTrait::foo')

getPropertyDeclaringClass (ReflectionProperty $prop): ReflectionClass

プロパティ $prop の宣言を含むクラスまたはトレイトのリフレクションを返します。プロパティはトレイト内で宣言されることもあります。

PHPは実際の宣言を特定するための十分な情報を提供しないため、Netteは信頼できるとは限らない独自のヒューリスティックを使用します。

trait DemoTrait
{
	public $foo;
}


class DemoClass
{
	use DemoTrait;
}

$prop = new ReflectionProperty(DemoClass::class, 'foo');
Reflection::getPropertyDeclaringClass($prop); // ReflectionClass('DemoTrait')

isBuiltinType (string $type)bool

$type がPHPの組み込み型かどうかを調べます。そうでない場合は、クラス名です。

Reflection::isBuiltinType('string'); // true
Reflection::isBuiltinType('Foo');    // false

Nette\Utils\Validator::isBuiltinType() を使用してください。

toString ($reflection): string

リフレクションを人間が読める文字列に変換します。

$func = new ReflectionFunction('func');
echo Reflection::toString($func); // 'func()'

$class = new ReflectionClass('DemoClass');
echo Reflection::toString($class); // 'DemoClass'

$method = new ReflectionMethod('DemoClass', 'foo');
echo Reflection::toString($method); // 'DemoClass::foo()'

$param = new ReflectionParameter(['DemoClass', 'foo'], 'param');
echo Reflection::toString($param); // '$param in DemoClass::foo()'

$prop = new ReflectionProperty('DemoClass', 'foo');
echo Reflection::toString($prop); // 'DemoClass::$foo'
バージョン: 4.0