Error using $this in static function

Asked

Viewed 219 times

0

I’m trying to use a class function as follows:

$database = database::select("SELECT * FROM eventos");

When I run the code, it returns the error:

Fatal error: Using $this when not in Object context in /var/www/html/folder/class/config.php online 27

The class is as follows:

<?php
class database{

    protected static $driver = 'mysql';
    protected static $host = 'localhost';
    protected static $port = 3306;
    protected static $user = 'root';
    protected static $pass = 'vertrigo';
    protected static $database = 'noweb';
    public $link = null;

    public function __construct(){

        try{

            $this->link = new PDO(self::$driver.":host=".self::$host.";port=".self::$port.";dbname=".self::$database, self::$user, self::$pass);

        }catch(PDOException $i){

            die("Ocorreu um erro ao fazer conexão: <code>".$i->getMessage()."</code>");
        }

    }

    static function select($sql){

        $query = $this->link->query($sql);
        $rs = $query->fetchAll(PDO::FETCH_OBJ) or die(print_r($query->errorInfo(), true));

        return $rs;
    }
}

?>

How can I arrange this, since I want to call the duties of this class as follows:

database::FUNÇÃO('parametros');
  • Transform $link in static property and exchange the occurrences of $this for self

  • @rray did it $query =self::$link->query($sql); and he returns me Fatal error: Call to a Member Function query() on a non-object

  • Solved. I was able to solve by throwing the connection to a static function called connexion() and taking the connection from __Construct(); thus, in the function select(){ } I called the function self:connexion();

2 answers

2


Because static methods can be called without an instance of the object being created, the $this pseudo-variable is not available within the method declared as static.

Static properties cannot be accessed by the object using the arrow operator ->.

Calling non-static methods statically generates a level warning E_STRICT.

Like any other PHP static variable, static properties can only be initialized using a literal or constant value; expressions are not allowed. Then you can initialize a static property for an integer or array (for example), you cannot initialize with another variable, with a function return, or an object. source: PHP

0

In your example, there is a static method that attempts to access an attribute of an instance(object) at some point was creating the object? not soon $this->algo will not be accessible.

Recommended reading:

When to use self vs $this in PHP?

Browser other questions tagged

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