0

我正在尝试在我的 Web 开发项目中实现 PHP 链接方法。但我似乎无法做到这一点。

class foo extends base{


    public $query = null;
    public $item = array();

    public function __construct($connection){
        parent::__construct($connection);

    }

    public function select($query){
         $this->query = $query;
         return $this;
    }

    public function where($query){
         $this->query = $query;
         return $this;
    }

    public function __toString()
    {
        $this->item = $this->connection->fetch_assoc($this->query);

        return var_export($this->item, true);
    }


}

$connection = new db($dsn = 'mysql:host=localhost;dbname=xxx',$username = 'xxx',$password = 'xxx');
$foo = new foo($connection);

$select = $foo->select("SELECT * FROM page")->where("page_id = 10 ");
print_r($select->item);

我得到的结果,

Array
(
)

但我应该得到一行数据。就像我平时那样做

class boo extends base{

    ...

    public function select() {

        $sql = "
            SELECT * 
            FROM page
            WHERE page_id = ?
        ";

        $item = $connection->fetch_assoc($sql,array(1));
        return $item;

    }
}

我在链接方法中遗漏了什么?

编辑:

class base
{
    protected $connection = null;

    public function __construct($connection)
    {
        $this->connection = $connection;

    }


}

如果我只是打印$select

print_r($select);

结果,

foo Object
(
    [query] => where page_id = 10 
    [item] => Array
        (
        )

    [connection:protected] => db Object
        (
            [connection] => PDO Object
                (
                )

            [dsn] => mysql:host=localhost;dbname=xxx
            [username] => xxx
            [password] => xxx
        )

)
4

2 回答 2

0

试试喜欢

$select = $foo->select('*')->from('page')->where('page_id','10');
print_r($select);
于 2013-08-24T07:36:44.947 回答
0

通过以下调用,您所做的就是设置和替换foo$query成员变量的值:

$select = $foo->select("SELECT * FROM page")->where("page_id = 10 ");

因此,$foo->select("SELECT * FROM page")设置$query成员变量的值,然后->where("page_id = 10 ")替换该值。

此外,您没有执行查询。

于 2013-08-24T07:40:24.430 回答