【发布时间】:2015-11-02 20:49:11
【问题描述】:
我想在 for 循环中创建一个类的对象,但我不知道我在做什么错。 这是我的选择功能。
public function admin_select_all ($table, $rows = '*', $where = null, $order = null)
{
if(empty($table))
{
return false;
}
$q = 'SELECT '.$rows.' FROM '.$table;
if($where != null)
$q .= ' WHERE '.$where;
if($order != null)
$q .= ' ORDER BY '.$order;
if($this->admin_tableExists($table))
{
$stmt = $this->admin_connection->prepare($q);
$stmt->execute();
$results = $stmt->fetchAll();
if( (!$results) or (empty($results)) ) {
return false;
}
return $results;
}
}
这是 admin_element 类的构造函数
public function __construct($itemId)
{
global $db_operate;
$info = $db_operate->admin_select_all ("my_table" ,"id=".$itemId);
$this->id = $info[0]['id'];
$this->title = $info[0]['title'];
$this->seoUrl = $info[0]['seo_url'];
$this->parentId = $info[0]['parent_id'];
$this->isMenuItem = $info[0]['menu_item'];
$this->order = $info[0]['menu_order'];
$this->htmlId = $info[0]['anchor_unique_html_id'];
}
//这是admin_element里面的函数,我想在for循环里面创建一个对象
public static function getRootItems()
{
global $db_operate;
$parents = $db_operate->admin_select_all ("my_table");
$listOfItems = array();
for($i=0;$i<count($parents);$i++)
{
$listOfItems[$i] = new admin_element($parents[$i]['id']);
}
//var_dump($listOfItems);
return $listOfItems;
}
}
现在,当我用这个创建一个对象时,我在构造函数中得到错误 undefined id,当我 var_dump 数组时,我得到的错误等于我返回的数组的总长度 $parent。我不知道我在做什么错。我也用 foreach 尝试过,但仍然没有成功。
//用foreach我试了一下,但无法创建和对象
foreach($parents as $row) {
$listOfItems[] = array(
'id' => $row['id']
);
}
在这里,当我对 $listOfItems 数组进行 var_dump 时,它运行良好,但是当我尝试实例化对象时,它也失败了,请帮忙。如果在我道歉之前有人问过这个问题。
【问题讨论】:
-
$q .= ' WHERE '.$where;你不知道Little Booby Drop Table吗? -
我知道检查函数参数的 $where 来自那里
-
您在
$info = $db->select("my_table" ,id=".$itemId);中有id=".$itemId的语法错误 -
在 foreach 中,您可以以相同的方式创建对象(仅没有 $i)。向我们展示完整的错误代码
-
var_dump($info)显示什么?