2017-10-29 4 views
0

文字列から関数を呼び出す際にいくつかの問題があります。関数を呼び出すよりもはるかに複雑なので、別のクラスで別の名前空間を使用する必要があります。PHP:名前空間を持つ別のクラス関数を呼び出していますか?

私はこのメソッドを使用して私のルートをディスパッチしますが、GitHubでTreeRouteパッケージを使用しています。

public function dispatch() { 
    $uri = substr($_SERVER['REQUEST_URI'], strlen(implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/')); 
    $method = $_SERVER['REQUEST_METHOD']; 

    $result = $this->router->dispatch($method, $uri); 

    if (!isset($result['error'])) { 
     $handler = $result['handler']; 
     $params = $result['params']; 

     // TODO: Call the handler here, but how? 
    } 
    else { 
     switch ($result['error']['code']) { 
      case 404 : 
       echo 'Not found handler here'; 
       break; 
      case 405 : 
       echo 'Method not allowed handler here'; 
       $allowedMethods = $result['allowed']; 
       if ($method == 'OPTIONS') { 
        // OPTIONS method handler here 
       } 
       break; 
     } 
    } 
} 

私はこのようなルートを登録します。

public function __construct() { 
    $this->router = new \TreeRoute\Router(); 
} 

public function setRoutes() { 
    $this->router->addRoute('GET', '/test', 'App/Controllers/SomeController/test'); 
} 

私は何をしたいことは、クラスでの通話機能「試験」である「SomeController」、今のApp \コントローラ 『「SomeControllerはの名前空間』を有しています。

私はcalluserfuncを調べましたが、私は文字列フォーマットと名前空間でそれを行う方法を理解できませんでした。誰かが私を助けてくれますか?

http://php.net/manual/en/function.call-user-func.php

答えて

0

あなたは、このように完全なクラスパスでcall_user_funcを呼び出すことができます。

call_user_func('App\Controllers\SomeController::test', $arg1, $arg2) 
// or 
call_user_func(['App\Controllers\SomeController', 'test'], $arg1, $arg2) 
// or better 
use App\Controllers\SomeController; 
call_user_func([SomeController::class, 'test'], $arg1, $args2); 
0

を、私はこれが仕事をすると信じて

if (!isset($result['error'])) { 
    $handler = $result['handler']; 
    $params = $result['params']; 

    $method = substr(strrchr($handler, '/'), 1); // get the method's name from $handler string 
    $class = substr($handler, 0, -strlen($method)-1); // get the class name from $handler string 
    $class = str_replace('/', '\\', $class); // change slashes for anti-slashes 

    // then choose one of those : 

     // if your methods are static : 
     call_user_func_array([$class, $method], $params); 

     // otherwise : 
     (new $class)->{$method}(...$params); // needs php 7 
} 
関連する問題