我第一次尝试用PHP进行面向对象编程——我试图构建一个查询生成器对象,该对象根据对象的输入生成查询。我想这是最简单的。
我预计buildQuery函数定义$active_value=$this->getActive;
下的行将按照__construct()
方法为对象的active
属性分配1。。。没有用。。。我做错了什么来获得期望的结果,即buildQuery返回
select * from mytable where active=1
TIA!
class queryBuilder {
function __construct(){
$this->active=1;
}
public function active () {
$this->active=1;
}
public function inactive () {
$this->active=0;
}
public function getActive(){
return $this->active;
}
public function setActive($value){
$this->active->$value;
}
public function buildQuery() {
$active_value=$this->getActive();
$query="select * from mytable where active=$active_value";
return $query;
}
}
$init=new queryBuilder();
echo $init->buildQuery();
对问题编辑的响应
当我在浏览器中运行它时,我会得到select * from mytable where active=1
。根据你的问题,我认为这就是你所需要的。如果你想引用active(这可能是你最初问题中的拼写错误(,那么你需要将$query="select * from mytable where active=$active_value";
替换为:
$query="select * from mytable where active='$active_value'";
// this will output select * from mytable where active='1'
如果您希望这在MySQL中是一个布尔值,那么使用1与0应该足够了,但您可以强制转换:
$query="select * from mytable where active=CAST($active_value as BOOL)";
// this will output select * from mytable where active=CAST(1 as BOOL)
原始文本
首先,您需要使用->
而不是=
,其次,您需要调用函数:
// not: $active_value=$this=getActive;
$active_value=$this->getActive();
几条评论:
- 作为OOP中的一般规则,方法通常被分解为
do
、get
和set
。名称通常不同,但它们应该始终是动词。CCD_ 11和CCD_ - 如果您有方法
getActive
和setActive
,通常最好使用它们来修改对象本身的状态。出于性能等原因,也有例外,但一般来说,这是一个好主意,它会强制要求这些方法存在。因此,inactive
应为function inactive(){ $this->setActive(1);}
- 您几乎不应该将新变量分配给预定义的类。如果可以的话,总是提前声明变量(在类的第1行添加private$active;(
- 因为
$this->active
是一个布尔值,所以在实际添加到查询之前,它可能应该是TRUE或FALSE:$active_value = $this->getActive()? 1: 0;