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

时间:2018-02-17 16:16:40

标签: php url-routing

我很难在代码中找出错误。在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

当我尝试设置'类别'和'链接'到一个空数组,一切都按预期工作正常。

enter image description here

在RouteDispatcher.php中我有: enter image description here

也许我可能会遗漏一些非常明显的东西,对我的问题的任何支持都很受欢迎。

1 个答案:

答案 0 :(得分:1)

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

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

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

$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
    );
相关问题