在不在对象上下文中时使用 $this,在使用 call_user_func_array() 时

Using $this when not in object context, when using call_user_func_array()

我很难找出代码中的错误。 SO 上有一些类似的问题,但它们对我的具体问题没有太大帮助。我还用谷歌搜索了关于错误的所有可能的短语,但仍然没有快乐。 在 ProductCategoryController.php 我有:

namespace App\controllers\admin;


use App\classes\CSRFToken;
use App\classes\Request;
use App\classes\ValidateRequest;
use App\models\Category;

class ProductCategoryController
{
    public $table_name = 'categories';
    public $categories;
    public $links;

    public function __construct()
    {
        $obj = new Category();
        $total = Category::all()->count(); // total number of rows
        list($this->categories, $this->links) = paginate(3, $total, $this->table_name, $obj);
    }

    public function show() {
        return view('admin/products/categories',
            [
                'categories' => $this->categories,
                'links' => $this->links
            ]);
    }

}

我收到错误

using $this when not in object context

在第 27 行,我分配 'categories' => $this->categories'links' => $this->links

当我尝试将 'categories' 和 'links' 设置为空数组时,一切都按预期正常工作。

在 RouteDispatcher.php 我有:

也许我可能遗漏了一些非常明显的东西,非常感谢对我的问题的任何支持。

在您的调度程序中,您正在静态调用控制器的方法。

在您的代码中测试您的方法是否可在新实例上调用。然后在调用时不要继续重用那个新创建的实例。相反,您在 call_user_func_array 中使用 class 和方法名称 - 因此静态调用它,这会导致您的错误。

尝试将您的代码更改为更像这样的内容:

$controller = new $this->controller;
$method     = $this->method;

if(is_callable(array($controller, $method)))
    call_user_func_array(array($controller, $method), $params);

或移动 new:

if(is_callable(array($this->controller, $this->method)))
    call_user_func_array(
        array(new $this->controller, $this->method),
        $params
    );