How to solve "Call to a member function prepare ()"?

1

I'm finding the following error in the script below:

  

Fatal error: Call to a member function prepare () on null in C: \ wamp \ www \ cursophp \ object_address \ pdo_statement \ users.php on line 20

Code:

class Usuarios {

private $db;

public function _construct(){

    try{
        $this->$db = new PDO("mysql:dbname=blog;host=localhost", "root", "");

    }catch(PDOException $e){
        echo " Falha na conexão: ".$e->getMessage();
    }

}

public function selecionar($id) {

    $sql = $this->db->prepare("SELECT * FROM usuarios WHERE id=:id");
    $sql->bindValue(":id", $id);
    $sql->execute();

    $array = array();
    if($sql->rowCount() > 0){
        $array = $sql->fetch();
    }
    return $array;
}
    
asked by anonymous 19.09.2017 / 21:00

1 answer

3

The constructor of a class in PHP should be named two underlines followed by the word construct . In your code there is only one underline, this does not invoke the defined constructor but the default constructor. Therefore it does not start the $db property with the PDO instance.

Change:

public function _construct(){

To:

public function __construct(){
    
19.09.2017 / 21:06