Abdul Muheet Abdul Muheet - 7 months ago 15
PHP Question

Create an Object inside for loop

I want to create an object of class inside for loop but i can't figure out what wrong i am doing.
This is my select function.

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;
}


}


This is a constructor of class 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'];
}


//This is the function inside admin_element where i want to create an object inside for loop

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;
}
}


Now when i create an object with this then i am getting the error undefined id in the constructor, and when i var_dump the array then i get the error's equal to the total length $parent which is my returned array. I don't know what wrong i am doing . I also try it with foreach but still no success.

//With foreach i try it but not able to create and object

foreach($parents as $row) {
$listOfItems[] = array(

'id' => $row['id']


);

}


Here when i var_dump the $listOfItems array then it's working well but when i try to instantiate the object then it also fail please some help.If this question is asked before i apologize.

Answer

Try to replace this:

$listOfItems = array();
for($i=0;$i<count($parents);$i++)
{
    $listOfItems[$i] = new itrom_element($parents[$i]['id']);
}

With this:

foreach($parents as $parent)
    $listOfItems[]= new itrom_element($parent['id']);
Comments