首页 -> Zend PHP 5 认证指南 第二版 -> 第六章:PHP的面向对象技术 Object Oriented Programming in PHP 6.7 反射 Reflection
第六章:PHP的面向对象技术 Object Oriented Programming in PHP 6.7 反射 Reflection
2010-05-01 02:52:43
作者:Siemen

通过PHP的Reflection API的函数与对象,可以调查脚本代码,比如运行时检查函数和对象。

反射可以的通途很多;例如,它可以用来生成简单的文档,或者确认脚本中是否存在某个函数等。举例来说:

 
 
<h1>Documentation</h1>
 
name . '(';
 
  $args = array();
 
  foreach ($func->getParameters() as $param) {
    $arg = '';
    if ($param->isPassedByReference()) {
      $arg = '&';
    }
    if ($param->isOptional()) {
      $arg = '[' . $param->getName() . ' = ' . $param->getDefaultValue() . ']';
    } else {
      $arg = $param->getName();
    }
    $args[] = $arg;
  }
 
  $prototype .= implode(", ", $args) . ' )';
 
  echo  "<h2>$prototype</h2>";
  echo "
<p>
Comment:
</p>
<pre>
" . $func->getDocComment() . "

File: " .$func->getFileName(). "
Line: " .$func->getStartLine(). " - " . $func->getEndLine(). "

"; } ?>

以上简单的代码运行后得到脚本中所有用户自定义函数,同时抽出函数的的一些信息;结果看起来类似:

<h2>foo ( bar, [baz = Array] )</h2>
<p>
Comment:
</p>
<pre>
/**
 * Do Foo
 *
 * @param string $bar Some Bar
 * @param array $baz An Array of Baz
 */
 

File: PHPDocument1
Lines: 8 - 8

即便是需要反射类,也只需要依照同样原理使用ReflectionClass与ReflectionMethod:

/**
 * Greeting Class
 *
 * Extends a greeting to someone/thing
 */
class Greeting {
  /**
   * Say Hello
   *
   * @param string $to
   */
   function hello($to = "World")
   {
     echo "Hello $to";
   }
}
 
$class = new ReflectionClass("Greeting");
?>
<h1>Documentation</h1>
<h2>getName(); ?></h2>
<p>
Comment:
</p>
<pre>
getDocComment(); ?>
 

File: getFileName(); ?>
Lines: getStartLine(); ?> - getEndLine(); ?>

getMethods() as $method) { $prototype = $method->name . ’ ( ’; $args = array(); foreach ($method->getParameters() as $param) { $arg = ’’; if ($param->isPassedByReference()) { $arg = ’&’; } if ($param->isOptional()) { $arg = ’[’ .$param->getName(). ’ = ’ .$param->getDefaultValue(). ’]’; } else { $arg = $param->getName(); } $args[] = $arg; } $prototype .= implode(", ", $args) . ’ )’; echo "

$prototype

"; echo "

Comment:

" .$method->getDocComment(). "

File: " .$method->getFileName(). "
Lines: " .$method->getStartLine(). " - " .$method->getEndLine(). "

"; }

运行的结果应该是:

<h1>Documentation</h1>
<h2>Greeting</h2>
<p>
Comment:
</p>
<pre>
/**
 * Greeting Class
 *
 * Extends a greeting to someone/thing
 */

File: PHPDocument2
Lines: 7 - 18

hello ( [to = World] )

Comment:

/**
 * Say Hello
 *
 * @param string $to
 */

File: PHPDocument2
Lines: 13 - 17

反射API非常强大,不仅可以反射用户自定义的而且可以反射内部的函数、类与对象。

另外,在检索的同时,也可以通过API调用函数或者方法。