我正在尝试从数据库中检索数据的一些方法。我做了一个抽象类(ppdao),在这个类中,我有一个函数来构建基于表名的选择查询,并将结果转换为对象。
为每个表创建一个小文件,如下所示:
class user extends ppdao{
public $table = 'user';
public function __set ( $name, $value ){
$this->$name = $value;
}
public function __get ( $name ){
return $this->$name;
}
假设我想要所有的用户对象在一个数组中,我使用下面的函数从我的ppdao类:
public static function get_ar_obj( $arWhere = array() , $arWhereWay = array(), $order = null ){
$class = get_called_class();
$obj = new $class();
$sql = "SELECT * FROM ".$obj->table. $obj->arWheretoString($arWhere);
$res = mysqli_conn::getinstance()->query($sql)->all_assoc();
return $obj->createObjects($res);
}
一切正常,它给了我想要的结果。
现在我把__get函数改成了这样:
public function __get ( $name ){
switch ($name){
case 'oAlbums':
return $this->oAlbums = albums::get_ar_obj($arWhere = array('user_id' => $this->id) );
break;
default:
return $this->$name;
break;
}
我想获得一个用户拥有的所有专辑,在专辑表中有一个名为user_id的字段,所以我想我应该像这样将m链接在一起。
现在当我像这样调用相册类时:
$userobject->oAlbums
get_called_class()仍然使用用户类名而不是调用的专辑类,因此它创建了一个类似
的查询SELECT * FROM user WHERE user_id = 63
And it should be SELECT * FROM album WHERE user_id = 63
谁有任何想法,我如何才能得到这个工作?
对不起的人,它不使用get_called_class来创建查询,它使用公共$表。现在通过将其更改为get_called_class变量
使其工作结果如下:
$arUser = user::get_ar_obj( $arWhere = array('id' => 1));
$oUser = $arUser[0];
echo '<pre>';
print_r($oUser->oAlbums);
echo '</pre>';
输出:
Array
(
[0] => album Object
(
[table] => album
[data:ppdao:private] =>
[className:ppdao:private] => album
[id] => 2
[name] => My new album 1
[slug] => my-new-album-1
[user_id] => 1
[views] => 0
[datecreated] => 2013/03/23 16:00:43
[location] => Muaha
)
您看过static
关键字了吗?PHP5>= 5.3
public static function get_ar_obj( $arWhere = array() , $arWhereWay = array(), $order = null ){
$obj = new static();
$sql = "SELECT * FROM ".$obj->table. $obj->arWheretoString($arWhere);
$res = mysqli_conn::getinstance()->query($sql)->all_assoc();
return $obj->createObjects($res);
}