2017-04-21 11 views
0

laravelまたはslimルートのようなメソッドを呼び出すにはどうすればよいですか?オブジェクトなしで配列を使ってメソッドを呼び出す方法は?

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

を使用します。

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についての情報を提供し、そのうちのどの必須またはオプションされます。

更新:この例では、メソッドが静的であると想定しています。非静的の場合は、クラスの存在(で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'); 
関連する問題