2017-04-21 70 views
0

我怎樣才能調用laravel或苗條路線的方法?如何使用無對象的數組調用方法?

比方說,我有課是這樣的:

namespace App; 
class App 
{ 
    public function getApp(){ 
     return "App"; 
    } 
} 

,我想在這條路上

$route->get('App\App','getApp'); 

我怎麼能這樣叫?

+0

爲什麼你想這樣做呢? –

回答

0

最簡單的方法

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

php.net source call_user_func_array()

如果需要檢查,如果方法存在,只是用

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

php.net method_exists()

所以你Router類可能是下一個:

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 
    } 
} 

如果你想在更聰明的方式做,你可以使用Reflection,它會向您提供有關類/方法的存在,也給有關方法PARAMS信息,以及哪些是必需的或可選的。

更新:此示例預計方法是靜態的。對於非靜態,你可以添加檢查,在Router類,類存在(class_exists($類)),並且還水木清華這樣

$obj = new $class(); 
$obj->$method(); //For methods without params 

UPDATE(2)檢查了這一點去here和粘貼下一個代碼

<?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'); 
相關問題