2013-05-02 77 views
1

我有問題,我沒有想法如何解決這個問題。Mvc方法名稱必須是字符串

問題在這一行代碼:

public function ExecuteAction() { 
     return $this->{$this->action}(); 
    } 

所有其他做工精細控制器成功加載,但我對這個致命的錯誤。

Fatal error: Method name must be a string in D:\xampp\htdocs\Workplace\MVC\lib\BaseController.php on line 27

檢查我的代碼:

的index.php

$fController = new FController($_GET); 
$controller = $fController->CreateController(); 
$controller->ExecuteAction(); 

Fcontorler

public function createController() 
    { 
     if(class_exists($this->controller)) { 
      $parent = class_parents($this->controller); 
      if(in_array('BaseController', $parent)) { 
       if(method_exists($this->controller, $this->action)) { 
        return new $this->controller($this->action, $this->url); 
       }else { 
        echo "Method no exists"; 
       } 
      }else { 
       echo "Bad Controller"; 
      } 
     } else { 
      echo "Controller ". $this->controller . " class no exists"; 
     } 
    } 

BaseController

abstract class BaseController { 

    protected $urlvalues; 
    protected $action; 

    /* 
    * Construct 
    * 
    * @param string $action 
    * @param array $url 
    * 
    */ 

    public function __construct($action, $urlvalues) { 
     $this->action = $action; 
     $this->urlvalues = $urlvalues; 
    } 

    /* 
    * Execute acction 
    * 
    */ 

    public function ExecuteAction() { 
     return $this->{$this->action}(); 
    } 

localhost/Workplace/MVC/index.php?controller=hello&action=say&id=5

+0

如果將var_dump($ this-> action)放置在構造函數中,它會輸出什麼內容? – Shoe 2013-05-02 14:14:14

回答

0

var_dump($controller); object(Hello)#2 (2) { ["urlvalues":protected]=> NULL ["action":protected]=> NULL }

,因爲你要使用NULL而解釋期待一個字符串被觸發的錯誤。

隨着你var_dump顯示,$this->actionNULL因此串插$this->{$this->action}();被翻譯成$this->{NULL}();不能叫。

+0

查看完整的源代碼。 http://www.nathandavison.com/posts/view/9/custom-php-mvc-tutorial-part-3-controllers – Ivan 2013-05-02 14:18:18

相關問題