php - 在 PHP 中单行调用多个函数
问题描述
我所有连接到数据库的类都需要从各自的表中获取自定义列的值。因此,不是为每个类编写一个函数,有没有办法让我实现一个基类,我的类从中扩展,我可以使用该基类函数轻松获取和更新我的数据库中的数据(至少对于简单数据) .
class Users extend BaseClass
{
private $table = "users";
private $columns = ["name", "email", "password"];
}
所以从外部功能,我可以像这样访问电子邮件值
Users->where("name", "John")->getEmail();
或者可能
Users->where("name", "John")->get("email");
我也可以使用这种方法将数据更新到数据库中。这些功能where
应该是通用的,因此它应该存在于BaseClass
. (我知道我应该使用的数据库查询,我想知道的是如何在调用get
后调用where
以及可能设置多个 where 要求)。
Users->where("name", "John")->where("last_name", "Smith")->get("email");
解决方案
我想你想要这样的东西
abstract class BaseClass
{
private $where_clauses=[];
private $columns=[];
private $table='';
protected function setData($table,$cols){
$this->columns=$cols;
$this->table=$table;
}
public function where($key, $value){
$this->where_clauses[$key]=$value;
return $this;
}
public function get($col){
$sql='SELECT '.$col.' FROM '.$this->table.' WHERE';
$first=true;
foreach($this->where_clauses AS $key=>$val){
if(!$first) sql.=' AND ';
$first=false;
$sql.=$key.' = '.$val;
}
// RUN QUERY, Return result
}
}
请注意,该where
函数返回对 $this 的引用,这就是让您将函数调用串在一起的原因(未测试代码)。这还需要一些调整,让您将两个条件放在同一列上。