我想在循环内部创建一个类的对象,但我不知道我做错了什么。这是我的选择功能。
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中的函数,我想在其中为循环创建一个对象
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;
}
}
现在,当我用这个创建一个对象时,我会在构造函数中得到错误未定义的id,当我var_dump数组时,我得到的错误等于总长度$parent,这是我返回的数组。我不知道我做错了什么。我也用前臂试过,但还是没有成功。
//使用foreach,我尝试了一下,但无法创建和对象
foreach($parents as $row) {
$listOfItems[] = array(
'id' => $row['id']
);
}
在这里,当我var_dump$listOfItems数组时,它工作得很好,但当我尝试实例化对象时,它也失败了,请提供一些帮助。如果在我道歉之前有人问我这个问题。
尝试替换这个:
$listOfItems = array();
for($i=0;$i<count($parents);$i++)
{
$listOfItems[$i] = new itrom_element($parents[$i]['id']);
}
有了这个:
foreach($parents as $parent)
$listOfItems[]= new itrom_element($parent['id']);