使用pdo进行静态验证方法

Ive been converting some of my more basic scripts so they start utilizing PDO and I can't seem to get my static authenticate method to work. I have gotten it to work with it not being static, though.

Heres the relevent code with the non static authenticate method:

private $dbh;
public  function __construct()
{
    $this->dbh = new PDO("mysql:host=localhost;dbname=carmen", 'root', '');
    $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

 public function authenticate($username="", $password="")
 {
    $sql  = "SELECT * FROM user ";
    $sql .= "WHERE username = :username ";
    $sql .= "AND pass = :password ";
    $sql .= "LIMIT 1"; 

    $stmt = $this->dbh->prepare($sql);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return !empty($result) ?  true : false;
 }

My attempts at a solution usually run into problems at the first line after the sql statement when trying to declare the mehthod static. I'm guessing it has to deal with $dbh being declared private at the beginning of the class.

Your issue is that, once you've converted to a static method, $this->dbh isn't going to work.

If you want to make this method static, it will probably be easiest to just pass in your PDO object as a parameter to the function.

You can, instead, declare $dbh as a static variable, and then access it with self::$dbh, but then you'll also have to add some way to initialize it (likely another static method) instead of the constructor.

Static functions cannot access the $this pointer. It makes no sense in that context.

Some solutions are:

  • Keep the function non-static, or

  • Make the $dbh handle static. You would probably then replace the constructor with some sort of static init function, or

  • Pass the $dbh handle into the static functions that need it.

You may need to revisit your overall design.