Error "Using $this when not in Object context" in Slim framework

Asked

Viewed 1,760 times

0

I’m making the following mistake:

Fatal error: Using $this when not in Object context in C: Users PC Desktop slim_framework app Controllers Homecontroller.php on line 10

Composer.json

{
    "require": {
        "slim/slim": "^3.9",
        "slim/php-view": "^2.2"
    },
    "autoload": {
        "psr-4":{
            "App\\": "app"
        }
    }
}

index php.

<?php


use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';
require 'config/config.php';



$app = new \Slim\App(['settings' => $config]);



$container = $app->getContainer();
$container['view'] = new \Slim\Views\PhpRenderer("resources/views/");

require 'app/routes.php';

$app->run();

Routes.php

<?php

$app->get('/', 'App\Controllers\HomeController::index');

Controller.php

<?php

namespace App\Controllers;

class Controller {

    protected $container;

    public function __construct(\Slim\Container $container){
        $this->container = $container;
    }

    public function __get($propriedade){
        if($this->container->{$propriedade}){
            return $this->container->{$propriedade};
        }
    }

}

Homecontroller

<?php

namespace App\Controllers;
use App\Controllers\Controller;

class HomeController extends Controller{


    public function index($request, $response){
        $response = $this->view->render($response, 'template.phtml');
        return $response;
    }

}

I’m using php 5.4

1 answer

2


I believe that instead (::):

  $app->get('/', 'App\Controllers\HomeController::index');

You must do it (:):

  $app->get('/', 'App\Controllers\HomeController:index');

Because with the :: the Slim will try to call the method as if it were static, ie using so HomeController:index for Slim would be the same as:

<?php

$x = new HomeController;
$x->index();

What would be an instantiated object, and so on HomeController::index would be the same as calling it so:

<?php

HomeController::index();

This last way makes the method not recognize the $this, since it is not an object, so it will not be accessible in the context.

Note: if you were with the E_STRICT enabled would receive this following error message:

Strict Standards: Non-static method Homecontroller::index() should not be called statically in c: slim vendor slim slim Slim Handlers Strategies Requestresponse.php on line 32

Strict Standards: call_user_func() expects Parameter 1 to be a Valid callback, non-static method Homecontroller::index() should not be called statically in c: slim vendor slim slim slim Handlers Strategies Requestresponse.php on line 41

  • 1

    Vlw for help, now it worked right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.