【问题标题】:Simple OOP and PHP not working... can anyone help? :)简单的 OOP 和 PHP 不起作用……谁能帮忙? :)
【发布时间】:2011-08-08 16:45:53
【问题描述】:

我第一次使用 PHP 涉足 OOP - 我正在尝试构建一个查询构建器对象,该对象根据对象的输入生成查询。我想这很简单。

我希望 buildQuery 函数定义 $active_value=$this->getActive; 下的行会根据 __construct() 方法将 1 分配给对象的 active 属性...无济于事...我做错了什么来实现所需结果,即 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();

【问题讨论】:

  • 所以您将其编辑为@cwallenpoole,我发布了我们的答案。上面的代码现在是否正确,如 $active_value=$this->getActive();
  • 它在做什么而不是返回正确的$query
  • 你运行的是哪个版本的php?如果你正在运行 php4(你不应该),__construct() 不可用。

标签: php oop constructor


【解决方案1】:

对问题编辑的回应

当我在浏览器中运行它时,我得到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();

几个cmets:

  • 作为 OOP 中的一般规则,方法通常分为 dogetset。名称通常不同,但它们应该始终是动词。 inactiveactive 不是很直观。
  • 如果您有方法getActivesetActive,使用它们来修改对象本身的状态通常是个好主意。出于性能原因等原因也有例外,但通常这是一个好主意,并且它会强化这些方法的存在。 inactive 因此,应该是 function inactive(){ $this->setActive(1);}
  • 您几乎不应该将新变量分配给预定义的类。尽可能提前声明变量(在类的第 1 行添加 private $active;)
  • 因为$this->active 是一个布尔值,所以它应该是TRUE 或FALSE,直到它被实际添加到查询中:$active_value = $this->getActive()? 1: 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2013-08-02
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多