如何在Symfony中使用`IntlDateFormatter`?

问题描述

如何在Symfony 4.4中实现IntlDateFormatter

关于https://symfony.com/doc/current/components/intl.html,我已经安装了symfony/intl

现在,当我在代码中使用它时:

use Symfony\Component\Intl\DateFormatter\IntlDateFormatter;

    $formatter = new IntlDateFormatter(
        "de-DE",IntlDateFormatter::FULL,IntlDateFormatter::NONE,"Europe/Berlin",IntlDateFormatter::GREGORIAN,"MMMM YYYY"
    );

我得到Cannot instantiate abstract class Symfony\Component\Intl\DateFormatter\IntlDateFormatter。我知道抽象类不能实例化。但是我不确定如何实现。

解决方法

来自documentation

Composer自动在全局名称空间中公开这些类

如果我们检查源代码,这将更容易理解。在DateFormatter/IntlDateFormatter.php定义的类被标记为抽象,但是在Resources/stubs/IntlDateFormatter.php有一个实现如下:

use Symfony\Component\Intl\DateFormatter\IntlDateFormatter as BaseIntlDateFormatter;

/**
 * Stub implementation for the IntlDateFormatter class of the intl extension.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @see BaseIntlDateFormatter
 */
class IntlDateFormatter extends BaseIntlDateFormatter
{
}

简而言之,该类是根命名空间中的builin IntlDateFormatter的直接替代:

$fmt = new \IntlDateFormatter(...);
           ^

如果未安装扩展程序,则自动加载将自动加载Symfony的实现。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...