【问题标题】:php - how to call static class and function with variable?php - 如何使用变量调用静态类和函数?
【发布时间】:2018-05-12 06:22:30
【问题描述】:

我已经尝试过使用和不使用 {} 的代码,但它一直说“语法错误,意外'{',期待标识符 (T_STRING) in ..”

        $page = $_GET['page'];
        $do = $_GET['do'];

        {$page}::{$do}();

然后我有一个类和该类中应该调用的函数,如下所示。

class Example {
    public static function index()
    {}
}

所以如果 $page = "Example" 和 $do = "index" 我想调用 Example::index();

【问题讨论】:

  • 我还应该提到我有像 \namespace\Class::function(); 之类的命名空间;
  • call_user_func([$_GET["page"], $_GET["do]]) 并让任何人调用他们想要的任意静态函数。

标签: php static-methods


【解决方案1】:

有两种方法可以做到这一点:

//$class: the class which contains your static function
//$method: the function you want to call

call_user_func("$class::$method");
//OR
call_user_func(array($class, $method));

在你的情况下:

call_user_func("$page::$do");

call_user_func(array($page, $do));

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多