1

我有两个 PHP 文件,一个是“Pages.php”,class Pages{}第二个是“Core.php”,它有class Core{}. 我将“Pages.php”包含在“Core 类”的构造函数中,并尝试调用home()从“Pages 类”命名的公共方法。但它显示以下错误:

未捕获的错误:Core 类的对象无法转换为字符串。

class Core {
    protected $currentController  = 'Pages';
    protected $currentMethod  = 'home';
    protected $params = [];

    public function __construct() {      
        require_once '../app/controllers/' . $this->currentController . '.php';
        
        $this->currentController = new $this->currentController();
  
        $this->currentController->$this->currentMethod();        

    }   
    
}

如果我调用这样的方法

$a = $this->currentMethod;

$this->currentController->$a();

它工作正常......但我想知道为什么我不能像这样调用方法$this->currentController->$this->currentMethod();

4

1 回答 1

2

由于解释的顺序,您不能使用此语法。

如果您想在一行中执行此操作,则可以使用{}将内容“解释”为一个块。

$this->currentController->{$this->currentMethod}();
于 2021-02-13T14:55:49.453 回答