开发者

Simple OOP and PHP not working... can anyone help? :)

My first foray into OOP with PHP - I am trying to build a query builder object that generates a query based on inputs to the object. I would imagine this is as simple as simple gets.

I expected that the line under the buildQuery function definition $active_value=$this->getActive; would assign 1 to the object's active attribute per the __construct() method... to no avail... what am i doing wrong to achieve the desired result i.e. buildQuery to return

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 func开发者_如何学运维tion 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();


Response to edit of question

When I run this in a browser, I get select * from mytable where active=1. I assume that is what you need based on your question. If you want active to be quoted (which might be a typo in your original question), then you'll need to replace $query="select * from mytable where active=$active_value"; with:

$query="select * from mytable where active='$active_value'";
// this will output select * from mytable where active='1'

If you want this to be a Boolean in MySQL, then use of 1 vs. 0 should be sufficient, but you can cast:

$query="select * from mytable where active=CAST($active_value as BOOL)";
// this will output select * from mytable where active=CAST(1 as BOOL)

Original text

Well, first you need to use -> instead of =, second you need to call the function:

// not: $active_value=$this=getActive;
$active_value=$this->getActive();

Couple of comments:

  • As a general rule in OOP, methods are generally broken down to do, get, and set. The names are often different, but they should always be verbs. inactive and active aren't really intuitive.
  • If you have methods getActive and setActive it is often a good idea to use them to modify the state of the object itself. There are exceptions for performance reasons and the like, but generally it is a good idea and it re-enforces that those methods are there. inactive therefore, should be function inactive(){ $this->setActive(1);}
  • You should almost never assign a new variable to a pre-defined class. Always declare variables up front when you can (add private $active; at line 1 of the class)
  • Because $this->active is a boolean, then it should probably be TRUE or FALSE until it is actually added to the query: $active_value = $this->getActive()? 1: 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜