Php 如何使用不带对象的数组调用方法?

Php 如何使用不带对象的数组调用方法?,php,laravel,routes,slim,Php,Laravel,Routes,Slim,如何调用类似于laravel或slim route的方法 假设我有这样的课: namespace App; class App { public function getApp(){ return "App"; } } 我想在这条路上打电话 $route->get('App\App','getApp'); 我该怎么做?最简单的方法 call_user_func_array(['App\App', 'getApp'], $params_if_needed)

如何调用类似于laravel或slim route的方法

假设我有这样的课:

namespace App;
class App
{
    public function getApp(){
        return "App";
    }
}
我想在这条路上打电话

$route->get('App\App','getApp');
我该怎么做?

最简单的方法

call_user_func_array(['App\App', 'getApp'], $params_if_needed);

若您需要检查方法是否存在,只需使用

method_exists('SomeClass','someMethod') // returns boolean

因此,您的路由器类可能是下一个:

class Router
{
     public function get($class, $method)
     {
          if($_SERVER['REQUEST_METHOD'] !== 'GET') {
              throw new SomeCustomNotFoundException();
          }

          if (!method_exists($class, $method)) {
              throw new SomeCustomNoMethodFoundException();
          }

          call_user_func_array([$class, $method], $_REQUEST); //with params
          // OR
          call_user_func([$class, $method]); //without params, not sure
     }
}
如果您想以更聪明的方式进行操作,可以使用,它将为您提供有关类/方法存在的信息,还将提供有关方法参数的信息,以及其中哪些参数是必需的或可选的

更新:此示例期望方法是静态的。对于非静态,您可以在Router类中添加类存在性检查(class_exists($class))并像这样执行smth

$obj = new $class();
$obj->$method(); //For methods without params
更新(2)要检查此代码,请执行并粘贴下一个代码

<?php

class Router
{
     public function get($class, $method)
     {
          if($_SERVER['REQUEST_METHOD'] !== 'GET') {
              throw new SomeCustomNotFoundException();
          }

          if(!class_exists($class)) {
              throw new ClassNotFoundException();
          }

          if (!method_exists($class, $method)) {
              throw new SomeCustomNoMethodFoundException();
          }

          call_user_func_array([$class, $method], $_REQUEST); //with params
          // OR
         //call_user_func([$class, $method]); //without params, not sure
     }
}

class Test
{
    public static function hello()
    {
        die("Hello World");
    }
}

$route = new Router();
$route->get('Test', 'hello');

为什么要这样做?