Error Call to a member function prepare

0

The connection to the database is working perfectly, but the getList method returns this error:

Fatal error: Uncaught Error: Call to a member function prepare() on null in /opt/lampp/htdocs/site/config/config.class.php:32 Stack trace: #0 /opt/lampp/htdocs/site/config/config.class.php(43): Conexao->getList() #1 {main} thrown in /opt/lampp/htdocs/site/config/config.class.php on line 32

I understood that this is on line 32, but I can not find anything wrong with this line, can someone please give me a hand? the code is below:

<?php 

class Conexao {

    private $sql,$user,$pass,$lista;

    public function __construct($sql = 'mysql:host=localhost;dbname=teste',$user = 'root', $pass = '') {

        $this->sql  = $sql;
        $this->user = $user;
        $this->pass = $pass;

    }

    public function Conecta(){

        try {

            new PDO($this->sql,$this->user,$this->pass);

        }catch(Exception $e) {

            var_dump($e);

        }

    }

    public function getList() {

        $this->lista = $this->Conecta()->prepare('SELECT * FROM outros');
        $this->lista->execute();
        $this->lista->fetchAll();

    }

}


$testando = new Conexao;
$testando->Conecta();
$testando->getList();
    
asked by anonymous 08.03.2017 / 23:59

1 answer

2

return is missing within Conecta , do so:

public function Conecta(){

    try {

        return new PDO($this->sql,$this->user,$this->pass);

    }catch(Exception $e) {
        var_dump($e);
    }

}

If not, the return will be null and will not have access to new PDO

You do not really need to call Connecta every time, you could create a variable to check if you've already instantiated the PDO class, like this:

<?php 

class Conexao {

    private $sql, $user, $pass, $lista, $pdo;

    public function __construct($sql = 'mysql:host=localhost;dbname=teste',$user = 'root', $pass = '') {

        $this->sql  = $sql;
        $this->user = $user;
        $this->pass = $pass;

    }

    public function Conecta(){

        //Verifica se já está conectado
        if ($this->pdo) {
            return $this->pdo;
        }

        try {

            $this->pdo = new PDO($this->sql,$this->user,$this->pass);

        }catch(Exception $e) {

            var_dump($e);

        }

        return $this->pdo;    
    }

And you do not have to call this line:

$testando->Conecta();

Since you are using Conecta internally in the class:

$testando = new Conexao;
$testando->getList();
    
09.03.2017 / 00:09