【问题标题】:Laravel 5 can't reach custom class functionLaravel 5 无法实现自定义类功能
【发布时间】:2015-12-19 11:36:54
【问题描述】:

我有一个关于 Laravel 5 的问题。我在 app 目录中新建了一个目录和文件。

App
    Helpers
        weather.php
    Http
        Controllers
            test.php

我想访问weather.php中的函数,但它不起作用。

天气.php

namespace App\Helpers

class Weather {

    public function test() {
        return "A";
    }
}

Test.php

namespace App\Http\Controllers;

class TestController extends Controller {

    public function bla() {
        return \App\Helpers\Weather\test();
    }
}

我收到一个找不到类的错误。希望有人可以帮助我,因为我不知道出了什么问题。

【问题讨论】:

  • 你在创建这个类后运行composer dump-autoload了吗?

标签: php laravel namespaces laravel-5


【解决方案1】:

在 Laravel 5.0 和 5.1 中,您不再需要运行 composer dump-autoload,因为新的 PSR-4 已经解决了这个问题。

我认为这是正确的做法:

在 Weather.php 中 - 注意:文件名应为 Weather.php

<?php namespace App\Helpers

class Weather {
   public function test() {
      return "A";
   }
}

在TestController.php中

 <?php namespace App\Http\Controllers;

 use App\Helpers\Weather;

 class TestController extends Controller {

    public function __construct(Weather $weather){
        $this->weather = $weather;
    }

    public function bla() {
        return $this->weather->test();
    }
 }

【讨论】:

    【解决方案2】:

    问题是这行不正确:

    return \App\Helpers\Weather\test();
    

    如果你想调用test方法你应该首先创建一个对象Weather的实例:

    namespace App\Http\Controllers;
    
    class TestController extends Controller {
    
        public function bla()
        {
            $w = new \App\Helpers\Weather();
    
            return $w->test();
        }
    }
    

    相反,如果你想直接在类上调用方法,你应该把这个方法设为静态:

    class Weather {
    
        public static function test() {
            return "A";
        }
    }
    

    这样称呼它:

    public function bla()
    {
        return \App\Helpers\Weather::test();
    }
    

    【讨论】:

      【解决方案3】:

      您的助手类应添加到autoload 部分composer.json。喜欢,

      autoload": {
          "files": [
              "app/Http/Helpers/weather.php"
          ]
      },
      

      【讨论】:

        【解决方案4】:

        我注意到weather.php 有一个小写的 w,它应该是大写的。也许这就是问题所在?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多