我想将以下函数转换为static.This函数在类中。它运作正常。
class LoginDBHandler extends DBConnection
{
private $loginObj;
private $table="user_login";
private $statement;
public function __construct()
{
parent::__construct();
$this->loginObj=new userLogin();
}
//Other Non-static Methods
public function authenticate($username,$password)
{
$password=password_hash($password,PASSWORD_BCRYPT,Config::$password_options);
$this->statement=$this->pdo->prepare("select * from $this->table where username=:username and password=:password and isActive=1");
$this->statement->bindParam(":username",$username);
$this->statement->bindParam(":password",$password);
$this->statement->execute();
$this->statement->fetchAll();
if($this->statement->rowCount()==1)
{
return true;
}
else
{
return false;
}
}
}
我以下面的方式尝试过。
class LoginDBHandler extends DBConnection
{
private $loginObj;
private $table="user_login";
private $statement;
public function __construct()
{
parent::__construct();
$this->loginObj=new userLogin();
}
//Other Non-static Methods
public static function authenticate($username,$password)
{
$password=password_hash($password,PASSWORD_BCRYPT,Config::$password_options);
$this->statement=self::$pdo->prepare("select * from $this->table where username=:username and password=:password and isActive=1");
$this->statement->bindParam(":username",$username);
$this->statement->bindParam(":password",$password);
$this->statement->execute();
$this->statement->fetchAll();
if($this->statement->rowCount()==1)
{
return true;
}
else
{
return false;
}
}
}
但PDO无法访问。我有其他非功能也使用PDO。我应该如何访问它?
DBConnection的
<?php
class DBConnection
{
protected $pdo;
public function __construct()
{
$this->pdo = new PDO("mysql:host=localhost; dbname=db_inventory;","root","");
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec("set names utf8");
}
}
?>
使用静态方法进行身份验证和其他数据库操作非静态方法是否合适?扩展类是好还是我应该为pdo使用getmethod?
答案 0 :(得分:1)
你不能在静态函数中使用$ this,你可以在静态方法中使用static或self。请查看文档了解更多信息。