猿问

从空值创建默认对象 - 代码点火器

你好,我在 codeigniter 工作,我尝试消除我网站上的警告,我阻止:


$groups = array();


    if ($bannished_groups) {

        foreach ($bannished_groups as $k => $bannished_group) {

            $groups[$k] = $this->group_model->GetGroupByID($bannished_group->groupid);

            $groups[$k]->db = $bannished_group;

        }

    }

我有错误:


从空值创建默认对象


我试图声明:


$groups[$k]->db = new stdClass();

但它不起作用,我阅读了其他答案,但对我没有帮助..


宝慕林4294392
浏览 134回答 1
1回答

犯罪嫌疑人X

似乎该方法$this->group_model->GetGroupByID($bannished_group->groupid);并不总是返回一个对象,即使您认为它确实如此:-)如果它返回null一个空字符串或false,你会得到那个错误。在尝试使用它之前先检查一下:foreach ($bannished_groups as $k => $bannished_group) {    // Get the object    $obj = $this->group_model->GetGroupByID($bannished_group->groupid);    if (!is_object($obj)) {        // It's not an object, skip it and move on to the next        continue;    }    $groups[$k] = $obj;    $groups[$k]->db = $bannished_group;}这将确保您的$groups-array 仅包含对象。如果您仍然想将其添加到数组中,只需将对象直接存储$groups[$k]在 -$obj变量中而不是中。不过道理是一样的。
随时随地看视频慕课网APP
我要回答