PHP 获取静态方法 [英] PHP get static methods

查看:38
本文介绍了PHP 获取静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 var 调用类方法(像这样):

i want to call a class method by a var (like this):

$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();

我在 php 手册中阅读了如何获取类的函数成员 (get_class_methods).但我总是让每个成员都没有信息,如果它是静态的.

i read in the php-manual how to get the function-members of a class (get_class_methods). but i get always every member without information if its static or not.

如何确定方法的上下文?

how can i determine a method´s context?

感谢您的帮助

推荐答案

使用类 反射类:

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) );

这将输出所有静态函数.

This will output all static functions.

或者如果你想确定一个给定的函数是否是静态的,你可以使用 ReflectionMethod 类:

Or if you want to determine whether a given function is static you can use the ReflectionMethod class:

在 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());

这篇关于PHP 获取静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆