Error "Using $ this when not in object context" in the Slim framework

0

I have the following error:

  

Fatal error: Using $ this when not in object context in   C: \ Users \ PC \ Desktop \ slim_framework \ app \ Controllers \ HomeController.php   online 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

    
asked by anonymous 26.11.2017 / 01:09

1 answer

2

I think that instead ( :: ):

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

You should do this ( : ):

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

<?php

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

What would be an instantiated object, and thus :: would be the same as calling it:

<?php

HomeController::index();

This last way causes the method not to recognize HomeController:index , since it is not an object, so it will not be accessible in context.

Note: If you were with HomeController::index enabled, you 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 statically called c: \ slim \ vendor \ slim \ slim \ Slim \ Handlers \ Strategies \ RequestResponse.php on line 41

    
26.11.2017 / 01:55