solariusmedia / nette-reflection
Nette Reflection:docblock 注释解析器和常用反射类
v2.4.2
2017-07-11 19:28 UTC
Requires
- php: >=5.6.0
- ext-tokenizer: *
- nette/caching: ^2.2 || ^3.0
- nette/utils: ^2.4 || ^3.0
Requires (Dev)
- nette/di: ^2.4 || ^3.0
- nette/tester: ^2.0
- tracy/tracy: ^2.4
Conflicts
- nette/nette: <2.2
This package is auto-updated.
Last update: 2024-09-06 17:26:28 UTC
README
使用 Composer 安装
composer require nette/reflection
最新的稳定版本需要 PHP 版本 5.6 或更高(兼容 PHP 7.0 和 7.1)。
如果您喜欢 Nette,请现在捐款。谢谢您!
如果您需要查找任何类的所有信息,反射是完成这项任务的正确工具。您可以轻松地找出任何类有哪些方法,这些方法接受哪些参数等。
// getting PDO class reflection $classReflection = new Nette\Reflection\ClassType('PDO'); // getting PDO::query method reflection $methodReflection = new Nette\Reflection\Method('PDO', 'query');
注释
反射实际上与注释有很大关系。注释写入到 phpDoc 注释中(必须使用两个开头的星号!)并以 @
开头。您可以注释类、变量和方法
/** * @author John Doe * @author Tomas Marny * @secured */ class FooClass { /** @Persistent */ public $foo; /** @User(loggedIn, role=Admin) */ public function bar() {} }
代码中有这些注释
@author John Doe
- 字符串,包含文本值'John Doe'
@Persistent
- 布尔值,其存在表示true
@User(loggedIn, role=Admin)
- 包含关联数组array('loggedIn', 'role' => 'Admin')
可以通过 hasAnnotation()
方法检查是否存在类注释
$fooReflection = new Nette\Reflection\ClassType('FooClass'); $fooReflection->hasAnnotation('author'); // returns true $fooReflection->hasAnnotation('copyright'); // returns false
可以使用 getAnnotation()
获取值
$fooReflection->getAnnotation('author'); // returns string 'Tomas Marny' $fooReflection->getMethod('bar')->getAnnotation('User'); // returns array('loggedIn', 'role' => 'Admin')
.[注意] 后者定义会覆盖前者,因此您始终会得到最后的那个。
可以使用 getAnnotations()
获取所有注释
array(3) {
"author" => array(2) {
0 => string(8) "John Doe"
1 => string(11) "Tomas Marny"
}
"secured" => array(1) {
0 => bool(true)
}
}