If you want to use method closures and don't have PHP 5.3, perhaps you find useful the following function
<?php
function get_method_closure($object,$method_name){
if(method_exists(get_class($object),$method_name)){
$func = create_function( '',
'
$args = func_get_args();
static $object = NULL;
/*
* Check if this function is being called to set the static $object, which
* containts scope information to invoke the method
*/
if(is_null($object) && count($args) && get_class($args[0])=="'.get_class($object).'"){
$object = $args[0];
return;
}
if(!is_null($object)){
return call_user_func_array(array($object,"'.$method_name.'"),$args);
}else{
return FALSE;
}'
);
//Initialize static $object
$func($object);
//Return closure
return $func;
}else{
return false;
}
}
?>
Here is how you would use it:
<?php
class foo{
public function bar($foo){
return strtolower($foo);
}
}
$foo = new foo();
$f = get_method_closure($foo,'bar');
echo $f("BAR");//Prints 'bar'
?>
リフレクション
目次
導入
PHP 5には完全なリフレクション APIが付属しており、 クラス、インターフェイス、関数、メソッド、そしてエクステンションについて リバースエンジニアリングを行うことができます。 さらに、このリフレクション APIは関数、クラス、メソッドに 関するドキュメントコメントも取得することができます。
リフレクション APIは、Zend Engineのオブジェクト指向エクステンション で、以下のクラスから構成されています。
<?php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?>
注意: これらのクラスに関する詳細については、次章を参照してください。
以下の例のコードを実行してみましょう。
例1 リフレクション APIの基本的な使用法
<?php
Reflection::export(new ReflectionClass('Exception'));
?>
上の例の出力は以下となります。
Class [ <internal> class Exception ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [6] {
Property [ <default> protected $message ]
Property [ <default> private $string ]
Property [ <default> protected $code ]
Property [ <default> protected $file ]
Property [ <default> protected $line ]
Property [ <default> private $trace ]
}
- Methods [9] {
Method [ <internal> final private method __clone ] {
}
Method [ <internal, ctor> public method __construct ] {
- Parameters [2] {
Parameter #0 [ <optional> $message ]
Parameter #1 [ <optional> $code ]
}
}
Method [ <internal> final public method getMessage ] {
}
Method [ <internal> final public method getCode ] {
}
Method [ <internal> final public method getFile ] {
}
Method [ <internal> final public method getLine ] {
}
Method [ <internal> final public method getTrace ] {
}
Method [ <internal> final public method getTraceAsString ] {
}
Method [ <internal> public method __toString ] {
}
}
}
Reflector
Reflector は、 すべてのエクスポート可能なリフレクションクラスが実装しているインターフェイスです。
<?php
interface Reflector
{
public string __toString()
public static string export()
}
?>
ReflectionException
ReflectionException は標準の Exception を継承しており、 リフレクション API によって投げられます。 固有のメソッドやプロパティは導入されていません。
ReflectionFunction
ReflectionFunctionクラスにより、 関数のリバースエンジニアリングが可能となります。
<?php
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
{
final private __clone()
public void __construct(string name)
public string __toString()
public static string export(string name, bool return)
public string getName()
public bool isInternal()
public bool isDisabled()
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()
}
?>
親クラスであるReflectionFunctionAbstract にも、 invoke() および invokeArgs()、export()、 isDisabled() を除くすべてのメソッドが存在します。
注意: getNumberOfParameters() と getNumberOfRequiredParameters() は PHP 5.0.3 で追加され、 invokeArgs() は PHP 5.1.0 で追加されました。
関数の内部を調べるために、まず、 ReflectionFunctionクラスのインスタンスを 生成する必要があります。 次にこのインスタンスの上のメソッドのどれかをコールすることができます。
例2 ReflectionFunctionクラスの使用法
<?php
/**
* 簡単なカウンタ
*
* @return int
*/
function counter()
{
static $c = 0;
return $c++;
}
// ReflectionFunction クラスのインスタンスを生成する
$func = new ReflectionFunction('counter');
// 基本情報を表示する
printf(
"===> The %s function '%s'\n".
" declared in %s\n".
" lines %d to %d\n",
$func->isInternal() ? 'internal' : 'user-defined',
$func->getName(),
$func->getFileName(),
$func->getStartLine(),
$func->getEndline()
);
// ドキュメントコメントを表示する
printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));
// static 変数があれば表示する
if ($statics = $func->getStaticVariables())
{
printf("---> Static variables: %s\n", var_export($statics, 1));
}
// 関数を呼び出す
printf("---> Invokation results in: ");
var_dump($func->invoke());
// export() メソッドを使用する方が良い知れない
echo "\nReflectionFunction::export() results:\n";
echo ReflectionFunction::export('counter');
?>
注意: invoke()メソッドは、 call_user_func()と同様に 可変長の引数をとります。
ReflectionParameter
ReflectionParameterクラスは、 関数またはメソッドのパラメータに関する情報を取得します。
<?php
class ReflectionParameter implements Reflector
{
final private __clone()
public void __construct(string function, string parameter)
public string __toString()
public static string export(mixed function, mixed parameter, bool return)
public string getName()
public bool isPassedByReference()
public ReflectionClass getDeclaringClass()
public ReflectionClass getClass()
public bool isArray()
public bool allowsNull()
public bool isPassedByReference()
public bool isOptional()
public bool isDefaultValueAvailable()
public mixed getDefaultValue()
public int getPosition()
}
?>
注意: getDefaultValue(), isDefaultValueAvailable(), isOptional() は PHP 5.0.3 で追加され、 isArray() は PHP 5.1.0で追加されました。 getDeclaringFunction() および getPosition() は PHP 5.2.3 で追加されました。
関数パラメータの内部を調べる際には、まず、 ReflectionFunction クラスまたは ReflectionMethod クラスのインスタンスを 作成する必要があります。 次に、配列のパラメータを取得するために、そのインスタンスの getParameters()メソッドを使用してください。
例3 ReflectionParameterクラスの使用
<?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 {\n".
" Class: %s\n".
" Allows NULL: %s\n".
" Passed to by reference: %s\n".
" Is optional?: %s\n".
"}\n",
$i, // $param->getPosition() は PHP 5.2.3 から使用可能です
$param->getName(),
var_export($param->getClass(), 1),
var_export($param->allowsNull(), 1),
var_export($param->isPassedByReference(), 1),
$param->isOptional() ? 'yes' : 'no'
);
}
?>
ReflectionClass
ReflectionClassクラスにより、 クラスやインターフェイスのリバースエンジニアリングが可能となります。
<?php
class ReflectionClass implements Reflector
{
final private __clone()
public void __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 stdclass newInstanceArgs(array 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()
}
?>
注意: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() および setStaticPropertyValue() は、PHP 5.1.0 で追加されました。 また、newInstanceArgs() は PHP 5.1.3 で追加されました。
クラスのイントロスペクションを行うには、まず ReflectionClass クラスのインスタンスを生成する必要があります。それから、 このインスタンスのメソッドをコールしてください。
例4 ReflectionClassクラスの使用法
<?php
interface Serializable
{
// ...
}
class Object
{
// ...
}
/**
* カウンタクラス
*/
class Counter extends Object implements Serializable
{
const START = 0;
private static $c = Counter::START;
/**
* カウンタを呼び出す
*
* @access public
* @return int
*/
public function count() {
return self::$c++;
}
}
// ReflectionClass クラスのインスタンスを生成する
$class = new ReflectionClass('Counter');
// 基本情報を表示する
printf(
"===> The %s%s%s %s '%s' [extends %s]\n" .
" declared in %s\n" .
" lines %d to %d\n" .
" having the modifiers %d [%s]\n",
$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()))
);
// ドキュメントコメントを表示する
printf("---> Documentation:\n %s\n", var_export($class->getDocComment(), 1));
// このクラスが実装しているインターフェースを表示する
printf("---> Implements:\n %s\n", var_export($class->getInterfaces(), 1));
// クラス定数を表示する
printf("---> Constants: %s\n", var_export($class->getConstants(), 1));
// クラスプロパティを表示する
printf("---> Properties: %s\n", var_export($class->getProperties(), 1));
// クラスメソッドを表示する
printf("---> Methods: %s\n", var_export($class->getMethods(), 1));
// このクラスがインスタンス化可能な場合、インスタンスを生成する
if ($class->isInstantiable()) {
$counter = $class->newInstance();
echo '---> $counter is instance? ';
echo $class->isInstance($counter) ? 'yes' : 'no';
echo "\n---> 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')と等価です。
ReflectionObject
ReflectionObject クラスにより、 オブジェクトのリバースエンジニアリングが可能となります。
<?php
class ReflectionObject extends ReflectionClass
{
final private __clone()
public void __construct(mixed object)
public string __toString()
public static string export(mixed object, bool return)
}
?>
ReflectionMethod
ReflectionMethodクラスにより、 クラスメソッドのリバースエンジニアリングが可能となります。
<?php
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
{
public void __construct(mixed class, string name)
public string __toString()
public static string export(mixed class, string name, bool return)
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()
// ReflectionFunctionAbstract から継承したメソッド
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クラスのインスタンスを 生成する必要があります。 次にこのインスタンスの上のメソッドのどれかをコールすることができます。
例5 ReflectionMethodクラスの使用
<?php
class Counter
{
private static $c = 0;
/**
* カウンタをインクリメントする
*
* @final
* @static
* @access public
* @return int
*/
final public static function increment()
{
return ++self::$c;
}
}
// ReflectionMethod クラスのインスタンスを生成する
$method = new ReflectionMethod('Counter', 'increment');
// 基本情報を表示する
printf(
"===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
" declared in %s\n" .
" lines %d to %d\n" .
" having the modifiers %d[%s]\n",
$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->getStartLine(),
$method->getEndline(),
$method->getModifiers(),
implode(' ', Reflection::getModifierNames($method->getModifiers()))
);
// ドキュメントコメントを表示する
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));
// static 変数があれば表示する
if ($statics= $method->getStaticVariables()) {
printf("---> Static variables: %s\n", var_export($statics, 1));
}
// メソッドを呼び出す
printf("---> Invokation results in: ");
var_dump($method->invoke(NULL));
?>
ReflectionProperty
ReflectionPropertyクラスにより、 クラスプロパティに関する リバースエンジニアリングが可能となります。
<?php
class ReflectionProperty implements Reflector
{
final private __clone()
public void __construct(mixed class, string name)
public string __toString()
public static string export(mixed class, string name, bool return)
public string getName()
public bool isPublic()
public bool isPrivate()
public bool isProtected()
public bool isStatic()
public bool isDefault()
public void setAccessible() /* PHP 5.3.0 以降 */
public int getModifiers()
public mixed getValue(stdclass object)
public void setValue(stdclass object, mixed value)
public ReflectionClass getDeclaringClass()
}
?>
注意: getDocComment() は PHP 5.1.0 で追加されました。 setAccessible() は PHP 5.3.0 で追加されました。
プロパティの内部を調べるために、まず、 ReflectionPropertyクラスのインスタンスを 生成する必要があります。 次にこのインスタンスの上のメソッドのどれかをコールすることができます。
例6 ReflectionPropertyクラスの使用
<?php
class String
{
public $length = 5;
}
// ReflectionProperty クラスのインスタンスを生成する
$prop = new ReflectionProperty('String', 'length');
// 基本情報を表示する
printf(
"===> The%s%s%s%s property '%s' (which was %s)\n" .
" having the modifiers %s\n",
$prop->isPublic() ? ' public' : '',
$prop->isPrivate() ? ' private' : '',
$prop->isProtected() ? ' protected' : '',
$prop->isStatic() ? ' static' : '',
$prop->getName(),
$prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);
// String のインスタンスを生成する
$obj= new String();
// 現在の値を取得する
printf("---> Value is: ");
var_dump($prop->getValue($obj));
// 値を変更する
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));
// オブジェクトをダンプする
var_dump($obj);
?>
例7 ReflectionProperty クラスを用いた、private および protected プロパティの値の取得
<?php
class Foo {
public $x = 1;
protected $y = 2;
private $z = 3;
}
$obj = new Foo;
$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* PHP 5.3.0 以降 */
var_dump($prop->getValue($obj)); // int(2)
$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* PHP 5.3.0 以降 */
var_dump($prop->getValue($obj)); // int(2)
?>
注意: privateまたはprotectedクラスプロパティの値の取得または設定を 行うと、例外がスローされます。
ReflectionExtension
The ReflectionExtensionクラスにより、 エクステンションのリバースエンジニアリングが可能となります。 実行時にロードされている全てのエクステンションを get_loaded_extensions()により取得することができます。
<?php
class ReflectionExtension implements Reflector {
final private __clone()
public void __construct(string name)
public string __toString()
public static string export(string name, bool return)
public string getName()
public string getVersion()
public ReflectionFunction[] getFunctions()
public array getConstants()
public array getINIEntries()
public ReflectionClass[] getClasses()
public array getClassNames()
public string info()
}
?>
メソッドの内部を調べるために、まず、 ReflectionExtensionクラスのインスタンスを 生成する必要があります。 次にこのインスタンスの上のメソッドのどれかをコールすることができます。
例8 ReflectionExtensionクラスの使用
<?php
// ReflectionExtension クラスのインスタンスを生成する
$ext = new ReflectionExtension('standard');
// 基本情報を表示する
printf(
"Name : %s\n" .
"Version : %s\n" .
"Functions : [%d] %s\n" .
"Constants : [%d] %s\n" .
"INI entries : [%d] %s\n" .
"Classes : [%d] %s\n",
$ext->getName(),
$ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
sizeof($ext->getFunctions()),
var_export($ext->getFunctions(), 1),
sizeof($ext->getConstants()),
var_export($ext->getConstants(), 1),
sizeof($ext->getINIEntries()),
var_export($ext->getINIEntries(), 1),
sizeof($ext->getClassNames()),
var_export($ext->getClassNames(), 1)
);
?>
reflectionクラスを拡張する
組み込みクラスの特別なバージョンを作成したい場合 (例えば、、エクスポートする際に、色づけしたHTMLを作成したり、 メソッドの代わりに簡単にアクセスできるメンバー変数を作成したり、 補助的なメソッドを作成したり、)、 Reflectionクラスを拡張することができます。
例9 組み込みクラスを拡張する
<?php
/**
* 独自の Reflection_Method クラス
*/
class My_Reflection_Method extends ReflectionMethod
{
public $visibility = array();
public function __construct($o, $m)
{
parent::__construct($o, $m);
$this->visibility = Reflection::getModifierNames($this->getModifiers());
}
}
/**
* デモクラス #1
*
*/
class T {
protected function x() {}
}
/**
* デモクラス #2
*
*/
class U extends T {
function x() {}
}
// 基本情報を表示する
var_dump(new My_Reflection_Method('U', 'x'));
?>
注意: 注意: Iコンストラクタを上書きした場合、 挿入するコードの前に 親クラスのコンストラクタをコールしわすれないようにしてください。 これを怠ると、以下のようなエラーを発生します。 Fatal error: Internal error: Failed to retrieve the reflection object
リフレクション
18-May-2009 09:00
12-Apr-2009 09:39
the newInstanceArgs function cannot call a class' constructor if it has references in its arguments, so be careful what you pass into it:
<?php
class Foo {
function __construct (&$arr) {
$this->arr = &$arr;
}
function createInstance () {
$reflectionClass = new ReflectionClass("Bar");
return $reflectionClass->newInstanceArgs(array($this, $this->arr));
}
function mod($key, $val) {
$this->arr[$key] = $val;
}
}
class Bar {
function __construct (&$foo, &$arr) {
$this->foo = &$foo;
$this->arr = &$arr;
}
function mod($key, $val) {
$this->arr[$key] = $val;
}
}
$arr = array();
$foo = new Foo($arr);
$arr["x"] = 1;
$foo->mod("y", 2);
$bar = $foo->createInstance();
$bar->mod("z", 3);
echo "<pre>";
print_r($arr);
print_r($foo);
print_r($bar);
echo "</pre>";
/*
Output:
Warning: Invocation of Bar's constructor failed in [code path] on line 31
Fatal error: Call to a member function mod() on a non-object in [code path] on line 58
*/
?>
29-Mar-2009 10:48
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.
So instead of:
<?php
use AppCore as Core;
$oReflectionClass = new ReflectionClass('Core\Singleton');
?>
You would type:
<?php
use AppCore as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>
28-Jan-2009 10:41
It should be noted that the 'filter' parameter in the getProperties(filter) method is expected to be of type long. Not sure why, but it doesn't function as a way of passing in a string to fetch a subset of properties by string match.
22-Jan-2009 03:47
Some may find this useful.
<?php
/**
* Recursive function to get an associative array of class properties by property name => ReflectionProperty() object
* including inherited ones from extended classes
* @param string $className Class name
* @param string $types Any combination of <b>public, private, protected, static</b>
* @return array
*/
function getClassProperties($className, $types='public'){
$ref = new ReflectionClass($className);
$props = $ref->getProperties();
$props_arr = array();
foreach($props as $prop){
$f = $prop->getName();
if($prop->isPublic() and (stripos($types, 'public') === FALSE)) continue;
if($prop->isPrivate() and (stripos($types, 'private') === FALSE)) continue;
if($prop->isProtected() and (stripos($types, 'protected') === FALSE)) continue;
if($prop->isStatic() and (stripos($types, 'static') === FALSE)) continue;
$props_arr[$f] = $prop;
}
if($parentClass = $ref->getParentClass()){
$parent_props_arr = getClassProperties($parentClass->getName());//RECURSION
if(count($parent_props_arr) > 0)
$props_arr = array_merge($parent_props_arr, $props_arr);
}
return $props_arr;
}
//USAGE
class A{
public $a1;
function abc(){
//do something
}
}
class AA extends A{
public $a2;
function edf(){
//do something
}
}
class AAA extends AA{
//may not have extra properties, but may have extra methods
function ghi(){
//ok
}
}
//$ref = new ReflectionClass('AAA'); $props = $ref->getProperties();//This will get no properties!
$props_arr = getClassProperties('AAA', 'public');//Use this
var_dump($props_arr);
/*
OUTPUT on PHP5.2.6:
array
'a1' =>
object(ReflectionProperty)[4]
public 'name' => string 'a1' (length=2)
public 'class' => string 'AAA' (length=3)
'a2' =>
object(ReflectionProperty)[3]
public 'name' => string 'a2' (length=2)
public 'class' => string 'AAA' (length=3)
*/
?>
06-Jan-2009 04:19
With PHP 5.3 protected or private properties are easy to access with setAccessible(). However, it's sometimes needed (e.g. Unit Tests) and here is a workaround for getValue():
<?php
$class = new ReflectionClass('SomeClass');
$props = $class->getProperties();
// $propsStatic = $class->getStaticProperties();
$myPrivatePropertyValue = $props['aPrivateProperty'];
?>
Note that it wont work if you access the property directly with getProperty().
29-Jul-2008 08:37
Be aware that calling the method newInstanceArgs with an empty array will still call the constructor with no arguments. If the class has no constructor then it will generate an exception.
You need to check if a constructor exists before calling this method or use try and catch to act on the exception.
20-Jun-2008 10:47
When your class extends a parent class you maybe want the name
of them. Using getParentClass() is maybe a bit confusing. When
you want the name as string try the following.
<?php
$class = new ReflectionClass('whatever');
$parent = (array) $class->getParentClass();
if(array_key_exists('name', $parent))
{
# name of the parent class
$parent = parent['name'];
}
else
{
# no parent class avaible
$parent = false;
}
?>
When you turn getParentClass() to an array it will result either
array(0 => false) when no parent class exist or
array('name' => 'name of the parent class'). Tested on PHP 5.2.4
11-May-2008 07:44
The note about the signature of the ReflectionParameter constructor is actually incomplete, at least in 5.2.5: it is possible to use an integer for the second parameter, and the constructor will use it to return the n-th parameter.
This allows you to obtain proper ReflectionParameter objects even when documenting code from extensions which (strangely enough) define several parameters with the same name. The string-based constructor always returns the first parameter with the matching name, whereas the integer-based constructor correctly returns the n-th parameter.
So, in short, this works:
<?php
// supposing the extension defined something like:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// returns the last parameter, whereas
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// always returns the first $y at position 2
?>
08-Apr-2008 09:32
I think there are still some limitations in the reflection abilities:
* ReflectionClass :: getConstants() returns an associative array with the constants and their values inside. I don't understand, why they don't use an object there, too (e.g. ReflectionConstant). The final effect is, that you aren't able to read out the DocComment of constants.
* There is no nice way to access the default values of properties. You can workaround a bit with get_class_vars(), but this just returns the values of public properties. No way to access protected or even private properties.
* PHP 5 has a nice feature called type hinting. This is completely omitted. You may ask, if a certain parameter is an array, but you won't get the denoted type hint.
Maybe this is, or will be extended. I hope so.
hth,
Niels
07-Apr-2008 10:34
PHP 5.3 will receive Java's setAccessible() functionality for accessing protected/privates.
17-Feb-2008 02:41
I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.
If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.
<?php
function unshift(){
$ref = new ReflectionFunction('array_unshift');
$arguments = func_get_args();
return $ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>
I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...
31-Jan-2008 10:47
Like Will Mason said for the ReflectionMethod's constants, there is filter constants for ReflectionProperty too:
ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE
that can be used in the ReflectionClass' method getProperties:
$class=new ReflectionClass("Foo");
$class->getProperties(
ReflectionProperty::IS_STATIC |
ReflectionProperty::IS_PUBLIC );
this obtains the publics (static or not) and the statics (public or not): this exlude the non static private properties.
04-Dec-2007 01:16
If you are getting
Fatal error: Trying to clone an uncloneable object of class ReflectionClass in …
Ensure that this is set.
zend.ze1_compatibility_mode=Off in php.ini
Thanks to anil who posted this on www.tecpages.com
03-Aug-2007 08:29
If you are looking for the long $filters for ReflectionClass::getMethods(), here they are. They took me a long time to find. Found nothing in the docs, nor google. But of course, Reflection itself was the final solution, in the form of ReflectionExtension::export("Reflection").
<?php
//The missing long $filter values!!!
ReflectionMethod::IS_STATIC;
ReflectionMethod::IS_PUBLIC;
ReflectionMethod::IS_PROTECTED;
ReflectionMethod::IS_PRIVATE;
ReflectionMethod::IS_ABSTRACT;
ReflectionMethod::IS_FINAL;
//Use them like this
$R = new ReflectionClass("MyClass");
//print all public methods
foreach ($R->getMethods(ReflectionMethod::IS_PUBLIC) as $m)
echo $m->__toString();
?>
25-Jul-2007 12:53
Signature of constructor of ReflectionParameter correctly is:
public function __construct(array/string $function, string $name);
where $function is either a name of a global function, or a class/method name pair.
18-Jul-2007 03:58
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :
1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"
05-Sep-2006 09:19
If you need to try to do something with the phpdoc or like the java notations in php4, you can create your own
'reflection functions'. This is a litle example of that.
<?php
/**
* Comment used to start a phpdoc
* @author Thiago Mata
* @package notations
*/
define( 'START_DOC' , '/**' );
/**
* Comment used to end a phpdoc
* @author Thiago Mata
* @package notations
*/
define( 'END_DOC' , '*/' );
/**
* Comment used to indicate a tag of phpdoc
* @author Thiago Mata
* @package notations
*/
define( 'TAG_DOC' , '@' );
/**
* This is a function maded in PHP4 to get the notations from some php file.
* Can use comments with many lines
*
* @author Thiago Mata
* @date 05/09/2006
* @package notations
* @param string $strFile
* @copyright open source
* @example <code> $arrNotations = getFileNotations( 'somefile.php' ); </code>
*/
function getFileNotations( $strFile )
{
$strText = file_get_contents( $strFile );
$arrText = explode( "\n" , $strText );
$arrNotations = array();
for ( $intCount = 0 ; $intCount < count( $arrText ) ; ++$intCount )
{
$strLine = $arrText[ $intCount ];
// inside the phpdoc //
if ( strpos( trim( $strLine ) , START_DOC ) === 0 )
{
++$intCount;
$strLine = $arrText[ $intCount ];
$arrNotation = array();
// while the phpdoc is not finished //
while ( ( strpos( trim( $strLine ) , END_DOC ) !== 0 ) and ( $intCount < count( $arrText ) ) )
{
// removing the tag doc from the line //
$strLine = substr( $strLine , strpos( $strLine , TAG_DOC ) );
// get the name of the tag //
$strName = substr( $strLine , 0 , strpos( $strLine , ' ' ) );
// get the value of the tag //
$strLine = substr( $strLine , strpos( $strLine , ' ' ) + 1 );
if ( strpos( trim( $strLine ) , '*' ) === 0 )
{
$strLine = substr( $strLine , strpos( $strLine , '*' ) + 1 );
}
$strLine = trim( $strLine );
if ( ! isset( $arrNotation[ $strName ] ) )
{
$arrNotation[ $strName ] = '';
}
else
{
if ( $strLine != '' )
{
$arrNotation[ $strName ] .= "\n";
}
}
$arrNotation[ $strName ] .= trim( $strLine );
++$intCount;
$strLine = $arrText[ $intCount ];
}
if ( $intCount < count( $arrText ) )
{
do
{
++$intCount;
$strLine = $arrText[ $intCount ];
}
while ( $strLine == '' );
// adding the notation to the next command line //
$arrNotations[ trim( $arrText[ $intCount ] ) ] = $arrNotation;
$intCount--;
}
}
}
return( $arrNotations );
}
print( '<pre>' . "\n" );
var_export( getFileNotations( __FILE__ ) );
print( '</pre>' . "\n" );
?>
<!-- OUTPUT
array (
'define( \'START_DOC\' , \'/**\' );' =>
array (
'' => 'Comment used to start a phpdoc',
'@author' => 'Thiago Mata',
'@package' => 'notations',
),
'define( \'END_DOC\' , \'*/\' );' =>
array (
'' => 'Comment used to end a phpdoc',
'@author' => 'Thiago Mata',
'@package' => 'notations',
),
'define( \'TAG_DOC\' , \'@\' );' =>
array (
'' => 'Comment used to indicate a tag of phpdoc',
'@author' => 'Thiago Mata',
'@package' => 'notations',
),
'function getFileNotations( $strFile )' =>
array (
'' => 'This is a function maded in PHP4 to get the notations from some php file.
Can use comments with many lines',
'@author' => 'Thiago Mata',
'@date' => '05/09/2006',
'@package' => 'notations',
'@param' => 'string $strFile',
'@copyright' => 'open source',
'@example' => '<code> $arrNotations = getFileNotations( \'somefile.php\' ); </code>',
),
)
-->
02-Jun-2006 08:09
I have written a function which returns the value of a given DocComment tag.
Full example:
<?php
header('Content-Type: text/plain');
class Example
{
/**
* This is my DocComment!
*
* @DocTag: prints Hello World!
*/
public function myMethod()
{
echo 'Hello World!';
}
}
function getDocComment($str, $tag = '')
{
if (empty($tag))
{
return $str;
}
$matches = array();
preg_match("/".$tag.":(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);
if (isset($matches[1]))
{
return trim($matches[1]);
}
return '';
}
$method = new ReflectionMethod('Example', 'myMethod');
// will return Hello World!
echo getDocComment($method->getDocComment(), '@DocTag');
?>
Maybe you can add this functionality to the getDocComment methods of the reflection classes.
08-Feb-2006 04:07
Beware, the Reflection reflects only the information right after compile time based on the definitions, not based on runtime objects. Might be obvious, wasn't for me, until the app throws the exception at my head.
Example:
<?php
class A {
public $a = null;
function set() {
$this->foo = 'bar';
}
}
$a = new A;
$a->set();
// works fine
$Reflection = new ReflectionProperty($a, 'a');
// throws exception
$Reflection = new ReflectionProperty($a, 'foo');
?>
28-Apr-2005 12:28
The wonderfull example code of russ collier works great until using it in combination with an interface or another abstract class, wich forces to define a function or variable in the loadable dynamic class, and the loaded class doesn't implement all the abstract functions. Ofcourse the class should not be used and an error should be reported, but the reported error is a Fatal error and is impossible to catch. This way it is impossible to, for example, generate an error message displaying the name of the file from wich the class is loaded.
Having dynamicly loadable classes with a forced interface can be very usefull when working on big projects or giving third parties the ability to provide new plugins. Considering this (imho) it would be nice to provide a clean error message to the writer of the plugin.
Please correct me if I'm wrong.
20-Oct-2004 03:40
Actually, aside from my inconsistent order of keywords in the 2 factory methods ;-) the Triangle::getInstance() method has 1 glaring flaw: it never actually sets the Triangle::$instance property. The correct way to implement a Singleton this way would be to replace Triangle::getInstance() with this:
<?php
static public function getInstance()
{
if ( null == self::$instance )
{
self::$instance = new self;
return self::$instance;
}
return self::$instance;
}
?>
18-Oct-2004 04:40
If you've ever wanted to do dynamic class loading in PHP5, especially when the class you're trying to dynamically load is a Singleton (and therefore you cannot use the new operator), you can do something like this example below, using the PHP5 Reflection API:
<?php
abstract class Shape
{
static public function makeShape( $shapeName )
{
$shapeInstance = null;
$shapeClass = new ReflectionClass( $shapeName );
$shapeMethod = $shapeClass->getMethod( 'getInstance' );
$shapeInstance = $shapeMethod->invoke( null );
$shapeClass = null;
$shapeMethod = null;
return $shapeInstance;
}
abstract public function doStuff();
}
class Triangle extends Shape
{
private static $instance = null;
private function __construct() { }
public static function getInstance()
{
if ( null == self::$instance )
{
self::$instance = new self;
}
return self::$instance;
}
public function doStuff() { }
}
$typeOfShape = 'Triangle';
$shape = null;
try
{
$shape = Shape::makeShape( $typeOfShape );
}
catch ( Exception $e )
{
print "Error creating shape '$typeOfShape'! " . $e->getMessage() . "\n";
}
if ( null != $shape )
{
// $shape will be an instance of Triangle
$shape->doStuff();
}
?>
So by changing the value of $typeOfShape you can dynamically load the appropriate Shape subclass at runtime, thus facilitating a sort of plug-in style architecture for your classes. You can just drop in new Shape subclasses and not have to modify any of the Shape class code to support them in its factory method makeShape() :-)
If your subclasses are all in separate files, you could even make the 'including' of these files dynamic as well, by adding these lines to the Shape::makeShape() method after the $shapeInstance is initialized:
<?php
ini_set( 'include_path', ini_get( 'include_path' ) . PATH_SEPARATOR .
'/path/to/your/php/class/include/files' );
/**
* Assuming your subclasses are in files called 'class_$shapeName.php' :-)
* Of course doing a dynamic require() could be a security problem depending
* on how you validate/clean your $shapeName method parameter (if at all ;-))
*/
require_once( "class_$shapeName.php" );
?>
