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?
And what other message information, such as the line that generated the error?
– Woss
Why don’t you leave it all static in class
ConnectDB
? Since you did so in the rest of the code– Costamilam
@Andersoncarloswoss error pointing to the `Connect::getPDO method()'
– Bruno Duarte
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
?– Woss