【问题标题】:Create an Object inside for loop在 for 循环中创建一个对象
【发布时间】: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-&gt;select("my_table" ,id=".$itemId); 中有id=".$itemId 的语法错误
  • 在 foreach 中,您可以以相同的方式创建对象(仅没有 $i)。向我们展示完整的错误代码
  • var_dump($info) 显示什么?

标签: php arrays oop


【解决方案1】:

尝试替换这个:

$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']);

【讨论】:

  • 他没有提到,有语法错误,所以它可能是编辑问题
  • 不,这不是问题,在这里粘贴我的问题时,我正在更改一些表名等,因此错误地删除了双引号。没关系,我已经编辑了你现在可以检查它
  • 主要问题是我如何在 for 或 foreach 循环中创建类的对象,我正在做的是磨损或 irihgt..一些建议
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多