Using $this when it’s not in the context of the object

Asked

Viewed 193 times

2

I am trying to create a PHP class that connects to the Mysql database and am getting the following error:

Fatal error: Using $this when not in Object context

Connectdb.class.php

class ConnectDB
{
    public $pdo;
    private $driver, $host, $port, $base, $user, $pass;

    public function __construct() {
        $this->setDriver('mysql');
        $this->setHost('localhost');
        $this->setPort('3306');
        $this->setBase('bsn');
        $this->setUser('root');
        $this->setPass('');
        $this->connect();
    }

    public function connect() {
        try {
            $this->pdo = new PDO("{$this->getDriver()}:host={$this->getHost()};port={$this->getPort()};dbname={$this->getBase()}", $this->getUser(), $this->getPass());
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
        } catch (PDOException $e) {
            die('Ocorreu um erro na conexão com o banco de dados.');
        }
    }

    public function setDriver($str) {
        $this->driver = $str;
    }

    public function setHost($str) {
        $this->host = $str;
    }

    public function setPort($str)   {
        $this->port = $str;
    }

    public function setBase($str)   {
        $this->base = $str;
    }

    public function setUser($str)   {
        $this->user = $str;
    }

    public function setPass($str)   {
        $this->pass = $str;
    }

    public function getPDO()    {
        return $this->pdo;
    }

    public function getDriver() {
        return $this->driver;
    }

    public function getHost() {
        return $this->host;
    }

    public function getPort() {
        return $this->port;
    }

    public function getBase() {
        return $this->base;
    }

    public function getUser() {
        return $this->user;
    }

    public function getPass() {
        return $this->pass;
    }
}

Manipulatedata.class.php

require_once('ConnectDB.class.php');
require_once('ITemplate.php');

class ManipulateData extends ConnectDB implements ITemplate
{
    public function __construct() {
        parent::__construct();
    }

    public static function select($query) {
        $stmt = parent::getPDO()->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public static function insert($query) {}

    public static function update($query) {}

    public static function delete($query) {}

    public static function doubleData($dados) {}
}  

I’m trying to run mine darlings thus:

print '<pre>';
print_r(ManipulateData::select('SELECT * FROM vagas'));  

What I’m doing wrong?

  • 1

    And what other message information, such as the line that generated the error?

  • Why don’t you leave it all static in class ConnectDB? Since you did so in the rest of the code

  • @Andersoncarloswoss error pointing to the `Connect::getPDO method()'

  • But the method getPDO is not static and you are calling from a static. If you have not urged the class, who should be $this?

1 answer

7


There’s a conceptual error. Almost every PHP code I see posted here makes that mistake. People do not understand what inheritance is and use it anyway. This class should not inherit from the other, it has no relation between them. This is gambiarra. I understand you learned this because almost all PHP code using OOP is wrong. So it’s best not to use OOP. Don’t use something you don’t know. Tools are only good when you know how to use them. In your case, make it simple that you will get better code. And in PHP rarely OOP is an advantage, after all it is a language of scripts, does not have the same difficulty of other languages. And this ITemplate seems pointless. There are other conceptual problems in the class, including the English name is wrong, but I won’t even bother because its existence is already a mistake. And I didn’t see much reason to capture an exception just to say that I couldn’t connect and shut down the application. Exception capture must occur to make something useful.

The mistake is just what was said, is using the $this outside an object. The $this is the object variable, all methods that access object data have this variable, are the instance methods. In class methods this variable is not available, so it does not exist, it cannot be used. His methods are all static, ie all class, and has not yet created an instance, therefore the $this not available. So it won’t work. So it works:

class ManipulateData extends ConnectDB {
    public function select($query) {
        $stmt = $this->getPDO()->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
$obj = new ManipulateData();
print_r($obj->select('SELECT * FROM vagas'));

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

But it’s still a very wrong concept. You could just plug into the socket, but you’re doing this:

Tomada cheio de penduricalho para encaixar o plugue

Browser other questions tagged

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