【问题标题】:Class 'App\Http\Controllers\IntlDateFormatter' not found找不到类“App\Http\Controllers\IntlDateFormatter”
【发布时间】:2016-05-15 07:28:06
【问题描述】:

我开发此代码以使用 php 查看德黑兰时间和日期:

$fmt = new IntlDateFormatter("fa_IR@calendar=persian", IntlDateFormatter::FULL,
    IntlDateFormatter::FULL, 'Asia/Tehran', IntlDateFormatter::TRADITIONAL);

    echo "Date: " . $fmt->format(time()) . "\n";

这段代码运行良好,但是我想在 Laravel 控制器的函数中使用它。

路线:

Route::get('/date', [
'as' => 'date', 'uses' => 'HomeController@date'
]);

控制器:

public function date() {
    $fmt = new IntlDateFormatter("fa_IR@calendar=persian", IntlDateFormatter::FULL,
    IntlDateFormatter::FULL, 'Asia/Tehran', IntlDateFormatter::TRADITIONAL);

    echo "Date: " . $fmt->format(time()) . "\n";
}

结果是:

找不到类“App\Http\Controllers\IntlDateFormatter”

我知道 Laravel 中没有 IntlDateFormatter 类,但我在这里使用 php 类。我的错误是什么?

【问题讨论】:

  • 请添加更多代码和解释
  • 尝试使用\IntlDateFormatter

标签: php date laravel persian persian-calendar


【解决方案1】:

这是在 Laravel 中使用自定义类的示例:

<?php
namespace YourProject\Services;
class IntlDateFormatter{
  public static function dateFormat(){
    /*Do your date formatting here and return desired result*/
  }
}

我假设您将此文件保存在 app 目录中。 接下来在别名数组中的 config/app.php 中,添加

'IntlDateFormatter'     => Artisanian\Services\IntlDateFormatter::class,

这样你就可以轻松调用dateFormat函数如下:

\IntlDateFormatter::dateFormat();

在您的控制器或视图中。

希望对你有所帮助。

祝你好运。

【讨论】:

    【解决方案2】:

    你需要导入你的类所在的命名空间。

    请记住,app\文件夹是 PSR-4 加载的,因此,例如,如果您的类定义在名为 IntlDateFormatter.php 的文件中,则需要将此文件放在您的 app\ 中的某个位置。然后在您的控制器中导入该类:

    // in your controller 
    namespace App\Http\Controllers;
    
    use App\{your class location}\IntlDateFormatter;
    

    【讨论】:

    • 它是一个标准的php类,我在没有app\{class name}的情况下使用,它工作正常,感谢您的回答。
    【解决方案3】:

    谢谢回复,忘记加了

    使用 IntlDateFormatter;

    所以通过添加解决了未找到的错误。

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 2016-06-02
      • 2018-05-02
      • 2017-07-12
      • 2019-04-14
      • 2015-12-18
      • 2017-11-29
      • 2017-08-10
      • 2020-04-13
      相关资源
      最近更新 更多