【问题标题】:Uncaught Error: Object of class Core could not be converted to string未捕获的错误:Core 类的对象无法转换为字符串
【发布时间】:2021-02-13 14:29:42
【问题描述】:

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

未捕获的错误: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();这样调用方法?

【问题讨论】:

    标签: php oop


    【解决方案1】:

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

    如果您想在一行中完成,可以使用{} 将内容“解释”为一个块。

    $this->currentController->{$this->currentMethod}();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-09
      • 2015-03-08
      • 2013-08-07
      • 2018-03-12
      • 2014-02-21
      • 1970-01-01
      • 2015-11-21
      相关资源
      最近更新 更多