反射 Reflection
反射可以简单理解为扫描类的属性、方法和注释的能力。
用法
PHP 为我们提供了丰富的方法,使我们可以方便的使用。
1 2 3 4 | $reflect = new ReflectionClass('App\Foo');
$reflect ->getMethods();
$reflect ->getDocComment();
……
|
ログイン後にコピー
应用
有时系统需要向用户提供内置方法文档说明来使用,那么我们则可以通过 PHP 反射实现。
创建内置函数类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class FooFunction{
public static function mondayTimeStamp(){
$targetTime = strtotime ('now');
$w = date ('w', $targetTime );
$w = ( $w == 0 ? 7 : $w );
return mktime (0,0,0, date ('m', $targetTime ), date ('d', $targetTime )-( $w -1), date ('Y', $targetTime ));
}
public static function mondayDate(){
return date ('Y-m-d', self::mondayTimeStamp());
}
}
|
ログイン後にコピー
扫描内置函数类,生成文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $reflect = new ReflectionClass('FooFunction');
$data = [];
$methods = $reflect ->getMethods();
foreach ( $methods as $method ){
$methodName = $method ->getName();
$methodDocStr = $reflect ->getMethod( $methodName )->getDocComment();
$pattern = "/[@a-zA-Z\\x{4e00}-\\x{9fa5}]+.*/u";
preg_match_all( $pattern , $methodDocStr , $matches , PREG_PATTERN_ORDER);
$data [] = [
'name' => $methodName ,
'doc' => $matches [0]
];
}
echo json_encode( $data );
|
ログイン後にコピー
结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | [
{
"name": "mondayTimeStamp",
"doc": [
"返回当前周周一时间戳",
"@ return false|string"
]
},
{
"name": "mondayDate",
"doc": [
"返回当前周周一日期",
"@ return false|string"
]
}
]
|
ログイン後にコピー
推荐教程:《PHP教程》
以上がPHP リフレクション メカニズムを使用して関数ドキュメントを取得するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。