Search code examples
phpurl-routing

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


I am having a hard time trying to figure the error in the code. There some similar issues on SO, but they did not help that much with my specific problem. I also googled every possible phrases regarding the error, yet still no joy. In ProductCategoryController.php I have:

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
            ]);
    }

}

I get error

using $this when not in object context

on line 27 where I assign 'categories' => $this->categories and 'links' => $this->links

When I try setting 'categories' and 'links' to an empty array, everything work fine as expected.

enter image description here

In the RouteDispatcher.php I have: enter image description here

Perhaps I may be missing something very obvious, any support with my problem is well appreciated.


Solution

  • In your dispatcher, you are calling your controller's method statically.

    In your code you test if your method is callable on a new instance. And then don't go on to reuse that newly created instance when calling. Instead you use the class and method name in call_user_func_array - and therefore call it statically, which results in your error.

    Try and change your code to something more like this:

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

    Or move the new:

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