Extending class ReflectionFunction to get source code of function
<?php
class Custom_Reflection_Function extends ReflectionFunction {
public function getSource() {
if( !file_exists( $this->getFileName() ) ) return false;
$start_offset = ( $this->getStartLine() - 1 );
$end_offset = ( $this->getEndLine() - $this->getStartLine() ) + 1;
return join( '', array_slice( file( $this->getFileName() ), $start_offset, $end_offset ) );
}
}
?>
拡張
組み込みクラスの特別なバージョンを作成したい場合 (例えば、エクスポートする際に色づけしたHTMLを作成したり、 メソッドの代わりに簡単にアクセスできるメンバー変数を作成したり、 補助的なメソッドを作成したり) は、クラスを拡張してみましょう。
例1 組み込みクラスを拡張する
<?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'));
?>
上の例の出力は、 たとえば以下のようになります。
object(My_Reflection_Method)#1 (3) {
["visibility"]=>
array(1) {
[0]=>
string(6) "public"
}
["name"]=>
string(1) "x"
["class"]=>
string(1) "U"
}
警告
コンストラクタを上書きする場合は、 挿入するコードの前に親クラスのコンストラクタをコールすることを忘れないようにしましょう。 これを怠ると、以下のようなエラーを発生します。 Fatal error: Internal error: Failed to retrieve the reflection object
khelaz at gmail dot com
28-Apr-2011 08:12
