为什么DateTime格式在我的第二个日期格式中作为非对象返回


Why does DateTime format return as a non-object on my second date format?

我收到一个错误,该错误仅在第二次调用此DateTime格式函数时显示。它在第一个调用上运行良好,这是我假设的,因为错误只发生在第二个调用的行上。

if( ! function_exists('month_dropdown')){
    function month_dropdown($field_name = 'month', $selected = '01', $value_format = 'm', $atts = ''){
        for($i=1;$i<=12;$i++){
            $numObj = DateTime::createFromFormat('!'.$value_format, $i);
            $val = $numObj->format($value_format);
            $nameObj = DateTime::createFromFormat('!F', $i);
            $text = $nameObj->format('F');
            $months[$val] = $text;
        }
        return form_dropdown($field_name, $months, $selected, $atts);
    }
}

这是我得到的错误:

Fatal error: Call to a member function format() on a non-object in ...application'frontend'helpers'MY_html_helper.php on line 73

第73行是定义变量$text的地方。

您使用了错误的格式化字符。对于月份整数,使用n

m和n

一个月的数字表示,带或不带前导零

示例:01到12或1到12

例如

$nameObj = DateTime::createFromFormat('!n', $i);
$text = $nameObj->format('F');

在这里演示~https://eval.in/188555