0xD*_*EEF 6 php reflection class-method
我想通过var调用类方法(像这样):
$var = "read";
$params = array(...); //some parameter
if(/* MyClass has the static method $var */)
{
echo MyClass::$var($params);
}
elseif (/* MyClass hat a non-static method $var */)
{
$cl = new MyClass($params);
echo $cl->$var();
}
else throw new Exception();
Run Code Online (Sandbox Code Playgroud)
我在php-manual中读到了如何获取类的函数成员(get_class_methods).但是我总是得到每个成员没有信息,如果它是静态的.
我如何确定方法的上下文?
谢谢您的帮助
Com*_*eek 17
使用课程ReflectionClass
:
On Codepad.org: http://codepad.org/VEi5erFw
<?php
class MyClass
{
public function func1(){}
public static function func2(){}
}
$reflection = new ReflectionClass('MyClass');
var_dump( $reflection->getMethods(ReflectionMethod::IS_STATIC) );
Run Code Online (Sandbox Code Playgroud)
这将输出所有静态函数.
或者,如果要确定给定函数是否为静态,则可以使用ReflectionMethod
该类:
在Codepad.org上:http://codepad.org/2YXE7NJb
<?php
class MyClass
{
public function func1(){}
public static function func2(){}
}
$reflection = new ReflectionClass('MyClass');
$func1 = $reflection->getMethod('func1');
$func2 = $reflection->getMethod('func2');
var_dump($func1->isStatic());
var_dump($func2->isStatic());
Run Code Online (Sandbox Code Playgroud)
我知道的一种方法是使用Reflection。特别是,这样使用ReflectionClass::getMethods
:
$class = new ReflectionClass("MyClass");
$staticmethods = $class->getMethods(ReflectionMethod::IS_STATIC);
print_r($staticmethods);
Run Code Online (Sandbox Code Playgroud)
这样做的困难在于您需要启用反射功能,默认情况下未启用它。
归档时间: |
|
查看次数: |
8678 次 |
最近记录: |