0

我正在尝试遍历父类中扩展类的不同选项,但我的 foreach 语句不断出现此错误:

警告:为 foreach() 提供的参数无效

不知道为什么会这样,知道我错过了什么吗?不知道为什么$this->options()不被识别为数组......我以前也做过类似的事情,但我认为这里有一些东西正在我的头上拍摄:

class parent_class {
    public function my_method() {
        $options = $this->options();
        foreach($options as $option) {
            // ...
        }
    }

    public function options() {
    }
}

class child_one extends parent_class {
    public function options() {
        $options['name_one'] = array(
            'type' => 'type_one',
            'id' => 'id_one',
            'name' => 'name_one'
        );
        return $options;
    }
}

class child_two extends parent_class {
    public function options() {
        $options['name_two'] = array(
            'type' => 'type_two',
            'id' => 'id_two',
            'name' => 'name_two'
        );
        return $options;
    }
}
4

1 回答 1

0

警告:为 foreach() 提供的参数无效

告诉你foreach期望提供一个数组作为第一个参数。您提供给它$options = $this->options(),由于该options()方法是空的,因此它的返回值是NULLsetting $options = NULL

为了避免它,你可以:

$options = $this->options();
if (is_array($options))
    foreach($options as $option) {
        // ...
    }
}
于 2013-02-09T23:45:59.160 回答