P
P
Pavel Novikov2018-03-14 13:43:09
PHP
Pavel Novikov, 2018-03-14 13:43:09

What might cause the PHP Uncaught Error: Using $this when not in object context error?

Good afternoon, I'm writing my own "framework" (I call it that for myself, but in fact it's just self-written garbage, I just write purely for myself to practice). And I ran into a problem that I can not understand.
I have class App. which is the parent of custom classes and methods, it looks like this

<?php
namespace App;
use Symfony\Component\Yaml\Yaml;
define('BASE_DIR', __DIR__ . '/../');
class App
{
    /**
     * @var Router
     */
    public $router;

    /**
     * App constructor.
     */
    public function __construct()
    {
        $this->router = new Router();
    }

    public final function run(){
        $this->router->match();
    }

    /**
     * @param string $view
     * @param array|null $parameters
     * @return string
     * @throws \Twig_Error_Loader
     * @throws \Twig_Error_Runtime
     * @throws \Twig_Error_Syntax
     */
    public function render(string $view, array $parameters = null) {
        $twig = new Twig();
        return $twig->render($view, $parameters);
    }

    /**
     * @param string $parameter
     * @return mixed
     */
    public function getParameter(string $parameter) {
        $file = Yaml::parseFile(BASE_DIR . 'config/config.yml');
        $parameters = $file['parameters'];
        return $parameters[$parameter];
    }
}

I also have my custom class, which is called when going to the main page
<?php
namespace Controller;
use App\App;
class AppController extends App
{

    public function indexAction() {
        return $this->render('index.twig', [
            'foo' => 'bar'
        ]);
    }
}

and as you may have guessed from the question, I get Fatal error Uncaught Error: Using $this when not in object context in /var/www/html/framework/src/Controller/AppController in line 12 ( when calling $this->render () )
What could be the problem, because I'm just inheriting a class that doesn't have any static methods or properties?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2018-03-14
@paulfcdd

You are calling the indexAction method statically. You must first create an AppController object on which to call it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question