
日期:2006-09-26 作者:喜騰小二 來源:PHPChina
介紹(Introduction)
PHP
5與一個API完全對應來以增加反嚮工程師類,介麵,函式和方法的效率(效能)並加以延伸。另外,
API對應並且為函式,類和方法提供獲取文檔注釋的方法。
API對應是對Zend引擎一個麵嚮物件的延伸。包括以下類:
PHP程式碼如下:
php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunction { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?>
注:為了詳細瞭解這些類,請看下一章。
如果我們將執行如下例子的程式碼:
例子 19-32.API對應的基本用法
PHP程式碼如下:
php
Reflection::export(new ReflectionClass('Exception'));
?>
上例將輸出:
[Copy to clipboard]CODE:
Class [
{
- Constants [0] { }
- Static properties [0] { }
- Static
methods [0] { }
- Properties [6] {
Property [
protected $message ]
Property [
Property [
Property [
protected $file ]
Property [
Property [
}
- Methods [9] {
Method [
Method [
-
Parameters [2] {
Parameter #0 [
Parameter #1 [
}
}
Method [
Method [
Method [
Method [
Method [
Method [
Method [
}
}
}
異常對應(ReflectionException)
ReflectionException
延伸標準異常並由API對應抛出。引入了非特定方法或內容。
對應函式(ReflectionFunction)
ReflectionFunction類允許妳反嚮設計函式。
PHP程式碼如下:
php
class ReflectionFunction implements Reflector
{
final private __clone()
public object __construct(string name)
public string __toString()
public static string export()
public string getName()
public bool isInternal()
public bool isUserDefined()
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public array getStaticVariables()
public mixed invoke(mixed* args)
public mixed invokeArgs(array args)
public bool returnsReference()
public ReflectionParameter[] getParameters()
public int getNumberOfParameters()
public int getNumberOfRequiredParameters()
}
?>
注:getNumberOfParameters()和getNumberOfRequiredParameters()在PHP5.0.3中增加,而invokeArgs()是在PHP5.1.0中增加。
為內省一個函式,您必須首先建立ReflectionFunction
類的一個實例。您可以隨後訪問這個實例中的任何上述方法。
例子 19-33. 使用ReflectionFunction 類
PHP程式碼如下:
php
/** A simple counter
* @return int */
function counter()
{ static $c = 0;
return $c++;
}
// Create an instance of the Reflection_Function class
$func = new ReflectionFunction('counter');
// Print out basic information
printf(
"===> The %s function '%s'
".
" declared in %s
".
" lines %d to %d
",
$func->isInternal() ? 'internal' : 'user-defined',
$func->getName(),
$func->getFileName(),
$func->getStartLine(),
$func->getEndline()
);
// Print documentation comment
printf("--->Documentation:
%s
",var_export($func->getDocComment(),1));
if ($statics=$func->getStaticVariables())//Print static variables if existant
{ printf("--->Static variables:%s
",var_export($statics,1)); }
printf("--->Invokation results in:");//Invoke the function
var_dump($func->invoke());
//you may prefer to use the export() method
echo "
ReflectionFunction::export() results:
";
echo ReflectionFunction::export('counter');
?>
注:方法invoke()透過象call_user_func()這樣的函式接受自變數的一個變化的數值。
對應參數
(ReflectionParameter)
ReflectionParameter類取回一個函式或方法的參數的資訊。
PHP程式碼如下:
php
class ReflectionParameter implements Reflector
{
final private __clone()
public object __construct(string name)
public string __toString()
public static string export()
public string getName()
public bool isPassedByReference()
public ReflectionClass getClass()
public bool isArray()
public bool allowsNull()
public bool isOptional()
public bool isDefaultValueAvailable()
public mixed getDefaultValue()
}
?>
注: 在PHP
5.0.3中增加了getDefaultValue(),
isDefaultValueAvailable()和isOptional(),而isArray()則是在PHP5.1.0中增加的。
為內省函式參數,妳必須首先建立ReflectionFunction或ReflectionMethod類的一個實例,然後用getParameters()方法來返回一個陣列型參數。
例子
19-34. Using the ReflectionParameter class
PHP程式碼如下:
php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }
//透過指令行用給定的參數建立ReflectionFunction的一個實例
$reflect = new ReflectionFunction($argv[1]);
echo $reflect;
foreach ($reflect->getParameters() as $i => $param)
{ printf( "-- Parameter #%d: %s {
".
" Class: %s
".
" Allows NULL: %s
".
" Passed to by reference: %s
".
" Is optional?: %s
".
"}
",
$i,
$param->getName(),
var_export($param->getClass(), 1),
var_export($param->allowsNull(), 1),
var_export($param->isPassedByReference(), 1),
$param->isOptional() ? 'yes' : 'no');
}
?>
對應類(ReflectionClass)
ReflectionClass類允許妳反嚮設計類。
PHP程式碼如下:
php
class ReflectionClass implements Reflector
{ final private __clone()
public object __construct(string name)
public string __toString()
public static string export()
public string getName()
public bool isInternal()
public bool isUserDefined()
public bool isInstantiable()
public bool hasConstant(string name)
public bool hasMethod(string name)
public bool hasProperty(string name)
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public ReflectionMethod getConstructor()
public ReflectionMethod getMethod(string name)
public ReflectionMethod[] getMethods()
public ReflectionProperty getProperty(string name)
public ReflectionProperty[] getProperties()
public array getConstants()
public mixed getConstant(string name)
public ReflectionClass[] getInterfaces()
public bool isInterface()
public bool isAbstract()
public bool isFinal()
public int getModifiers()
public bool isInstance(stdclass object)
public stdclass newInstance(mixed* args)
public ReflectionClass getParentClass()
public bool isSubclassOf(ReflectionClass class)
public array getStaticProperties()
public mixed getStaticPropertyValue(string name [, mixed default])
public void setStaticPropertyValue(string name, mixed value)
public array getDefaultProperties()
public bool isIterateable()
public bool implementsInterface(string name)
public ReflectionExtension getExtension()
public string getExtensionName()
}
?>
注
HP5.1.0中增加了hasConstant(),
hasMethod(), hasProperty(), getStaticPropertyValue()和
setStaticPropertyValue()。
為了內省一個類,妳必須首先建立ReflectionClass類的一個實例,妳可以隨後訪問這個實例任何上述方法。
例子
19-35. 使用ReflectionClass 的類
PHP程式碼如下:
php
interface Serializable { // ...}
class Object { // ...}
/** A counter class */
class Counter extends Object implements Serializable
{ const START = 0;
private static $c = Counter::START;
/**Invoke counter
* @access public
* @return int */
public function count() { return self::$c++; }
}
// Create an instance of the ReflectionClass class
$class = new ReflectionClass('Counter');
// Print out basic information
printf("===> The %s%s%s %s '%s' [extends %s]
" .
" declared in %s
" .
" lines %d to %d
" .
" having the modifiers %d [%s]
",
$class->isInternal() ? 'internal' : 'user-defined',
$class->isAbstract() ? ' abstract' : '',
$class->isFinal() ? ' final' : '',
$class->isInterface() ? 'interface' : 'class',
$class->getName(),
var_export($class->getParentClass(), 1),
$class->getFileName(),
$class->getStartLine(),
$class->getEndline(),
$class->getModifiers(),
implode(' ', Reflection::getModifierNames($class->getModifiers()))
);
// Print documentation comment
printf("--->Documentation:
%s
",var_export($class->getDocComment(),1));
// Print which interfaces are implemented by this class
printf("--->Implements:
%s
",var_export($class->getInterfaces(),1));
// Print class constants
printf("--->Constants:%s
",var_export($class->getConstants(),1));
// Print class properties
printf("--->Properties:%s
",var_export($class->getProperties(),1));
// Print class methods
printf("--->Methods:%s
",var_export($class->getMethods(),1));
// If this class is instantiable, create an instance
if ($class->isInstantiable())
{ $counter = $class->newInstance();
echo '---> $counter is instance? ';
echo $class->isInstance($counter) ? 'yes' : 'no';
echo "
---> new Object() is instance? ";
echo $class->isInstance(new Object()) ? 'yes' : 'no';
}
?>
注:方法newInstance()透過象call_user_func()這樣的函式接受自變數的一個變化的數值。
注
class=new
ReflectionClass('Foo');$class->isInstance($arg)等價於$arg instanceof
Foo或is_a($arg, 'Foo').
對應方法(ReflectionMethod)
ReflectionMethod類允許妳反嚮設計類方法。
PHP程式碼如下:
php
class ReflectionMethod extends ReflectionFunction
{ public __construct(mixed class, string name)
public string __toString()
public static string export()
public mixed invoke(stdclass object, mixed* args)
public mixed invokeArgs(stdclass object, array args)
public bool isFinal()
public bool isAbstract()
public bool isPublic()
public bool isPrivate()
public bool isProtected()
public bool isStatic()
public bool isConstructor()
public bool isDestructor()
public int getModifiers()
public ReflectionClass getDeclaringClass()
// Inherited from ReflectionFunction
final private __clone()
public string getName()
public bool isInternal()
public bool isUserDefined()
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public array getStaticVariables()
public bool returnsReference()
public ReflectionParameter[] getParameters()
public int getNumberOfParameters()
public int getNumberOfRequiredParameters()
}
?>
為了內省一個方法,妳必須首先建立ReflectionMethod類的一個實例。妳可以隨後訪問這個實例任何上述方法。
例子
19-36. Using the ReflectionMethod class
PHP程式碼如下:
php
class Counter
{ private static $c = 0;
/** Increment counter
* @final
* @static
* @access public
* @return int */ final public static function increment(){ return ++self::$c; }
}
// Create an instance of the Reflection_Method class
$method = new ReflectionMethod('Counter','increment');
// Print out basic information
printf( "===> The %s%s%s%s%s%s%s method '%s' (which is %s)
" .
" declared in %s
" .
" lines %d to %d
" .
" having the modifiers %d[%s]
",
$method->isInternal() ? 'internal' : 'user-defined',
$method->isAbstract() ? ' abstract' : '',
$method->isFinal() ? ' final' : '',
$method->isPublic() ? ' public' : '',
$method->isPrivate() ? ' private' : '',
$method->isProtected() ? ' protected' : '',
$method->isStatic() ? ' static' : '',
$method->getName(),
$method->isConstructor() ? 'the constructor' : 'a regular method',
$method->getFileName(),
$method->ge