Yamaha32088
Yamaha32088

Reputation: 4163

Call to member function on a non object

I am trying to learn OOP, currently rewriting a use login. I keep getting an error saying:

Fatal error: Call to a member function prepare() on a non-object in /var/www/new.php on line 22

Can someone point out what I did wrong? Also does this look like good OOP coding practice so far besides the obvious bug?

<?php  
ini_set('display_errors', TRUE);
require 'resources/library/DB.php';

    class DataBase
    {
        private $conn = null;

        public function __construct($conn)
        {
            $this->conn = $conn;
        }

            public function setConn($conn)
        {
            $this->conn = $conn;
            return $this;
        }

       public function retrievePassword($userNAme) 
       {
       $stmt = $this->conn->prepare('SELECT `password` FROM `users` WHERE `userName`= :userName');
       $stmt->bindValue(':userName', $userNAme);
       $stmt->execute();
       $salt = $stmt->fetchColumn();

       return $salt;
}
        }
    $db = new DataBase($conn);
    echo $db->retrievePassword('testuser');

?>  

Upvotes: 0

Views: 93

Answers (2)

Zack Newsham
Zack Newsham

Reputation: 2992

Your constructor is incorrect.

The correct PHP constructor is

__construct.

Thus when you call new Database($pdo), it uses the default constructor - which does no assignment.

Upvotes: 3

You are not passing your $conn to retrievePassword().

So it probably does not know what conn is.

Upvotes: 0

Related Questions