我看到了这些代码:
$result = $db->result($query);
$rows = $result->fetchAll();
我怎样才能达到类似的效果?($result包含方法?
我认为这就是您要查找的:
<?php
class test{
private $value = 0;
function foo(){
$this->value = 1;
return $this;
}
function bar(){
$this->value = 2;
echo $this->value;
}
}
$test = new test();
$result = $test->foo();
$result->bar();
?>
通过让方法返回自身,可以以这种方式将它们链接在一起。
严格来说,您是在问 PHP 中的 OOP,在这种情况下,这是一个合理的例子:
class HasResultMethod
{
public function result( $query )
{
return new HasFetchAllMethod();
}
}
class HasFetchAllMethod
{
public function fetchAll(){}
}
// you have a variable with a result method that has one parameter.
$result = $db->result($query);
// that returns an object which has a fetchAll method.
$rows = $result->fetchAll();
您可能正在处理一些围绕PDO
的包装器,一个与数据库接口的库。他们的query
方法将返回一个PDOStatement,其中包含允许您从数据库获取结果的方法。 result
要么是拼写错误,要么行为方式非常相似。
我已经明白了。多么棒的提示 头旋
http://sandbox.phpcode.eu/g/147bd.php
<?php
class foo{
function bar(){
return $this;
}
function fetch(){
echo "yeah";
}
}
$foo = new foo();
$result = $foo->bar();
$result->fetch();
很容易
$db是返回类的类的实例,所以当你说$db->结果($query(;
$db将返回对象
例如
//this method is inside $db class
function result($query)
{
$result = new Result();
$result->rows = mysql_query...
return $result;
}
当你说
$result->fetchAll((;
这是类 Result 中的方法,它将获取保存在 $result>行中的所有行;
例如
//method inside Result class
function fetchAll()
{
//fetch rows inside variable $this->rows
}
所以基本上你可以用ORM(对象关系映射(做什么,你可以返回对象数组,每个对象将代表来自db的一条记录
例如
Class User
{
var $ID;
var $Name;
var $LastName;
var $Email;
function load($row)
{
$this->ID = $row["ID"];
... etc
}
function save()
{
$sql = "update tbl_users set Name=:Name, LastName=:LastName, Email=:Email where ID=:ID";
//then execute your query
}
}
那么如何获取对象列表,它很容易
选择所有记录并将其添加到数组中
$ar = new Array();
for($i = 0; $i < count($rows); $i++)
{
$r = new User();
$r->load($rows[$i]);
}
return $ar;
就这么简单...