我正在尝试在我的 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
)
)