Error using $ this in static function

0

I'm trying to use a function from a class as follows:

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

When I run the code, it returns me the error:

Fatal error: Using this when not in context object in /var/www/html/folder/class/config.php on line 27

The class looks like this:

<?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 fix this, and I want to call the functions of this class as follows:

database::FUNÇÃO('parametros');
    
asked by anonymous 28.10.2015 / 22:53

2 answers

2

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

Static properties can not be accessed by the object using the arrow% -> operator.

Calling non-static methods in a static way generates a warning of level E_STRICT .

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

    
28.10.2015 / 23:04
0

In your example, is there 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?

    
28.10.2015 / 23:16