Reputation: 4163
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
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
Reputation: 68476
You are not passing your $conn
to retrievePassword()
.
So it probably does not know what conn
is.
Upvotes: 0