php - Fatal error: Using $this when not in object context but everything looks fine

618

I had this class:

<?php
class acController {

    protected $_enabledPages = array(
        'front_login.php',
    );

    protected $_enabledDirectories = array (
        'admin'
    );

    public static function isAuthorized() {
        echo '<pre>';
        acController::checkResource($_SERVER['SCRIPT_URI'], $this->_enabledDirectories);
        acController::checkResource($_SERVER['SCRIPT_URI'], $this->_enabledDirectories);
        echo '</pre>';
    }

    protected static function checkResource($urlAddress, $addressArray) {}
}

?>

And I got this error:

Fatal error: Using $this when not in object context

But when in this case $this is used within the class and I can't understand where is the problem. In other files I get the information withacController::isAuthorized();

Best regards, George!

854

Answer

Solution:

In a static function, you cannot $this.

$this implies existence of an object(instance of a class). While static implies a call to a class.

From the PHP documentation :

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

704

Answer

Solution:

You have a problem because your methods are statics. this represents an instance of the class but if you use it as static, the methods could be used without any instance of the class. So you can't this with statics.

People are also looking for solutions to the problem: ruby on rails - How do I specify some parameter while keeping the parameters before it default in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.