【发布时间】:2017-05-13 08:01:38
【问题描述】:
我想将以下函数转换为静态函数。这个函数在类中。它工作正常。
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 的非功能。我应该如何访问它?
数据库连接
<?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");
}
}
?>
使用静态方法进行身份验证和其他数据库操作非静态方法是否很好?扩展类好还是我应该将getmethod用于pdo?
【问题讨论】:
-
您不能在静态方法中使用任何对象属性。那是因为没有对象。所以你不能使用
$this。不过,您可以使用共享或静态属性。但是请记住,没有对象就不会执行构造函数。所以基本上静态方法不能真正依赖任何内部类,除了常量。