简体   繁体   English

Laravel 5无法达到自定义类功能

[英]Laravel 5 can't reach custom class function

I have a question about Laravel 5. I made a new directory and file in the app directory. 我有一个关于Laravel 5的问题。我在app目录中创建了一个新目录和文件。

App
    Helpers
        weather.php
    Http
        Controllers
            test.php

I want to access the function in weather.php but it doesn't work. 我想访问weather.php中的函数,但是不起作用。

Weather.php Weather.php

namespace App\Helpers

class Weather {

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

Test.php Test.php

namespace App\Http\Controllers;

class TestController extends Controller {

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

I get an error that the class is not found. 我收到一个找不到该类的错误。 Hope someone can help me because I don't know what is wrong. 希望有人可以帮助我,因为我不知道怎么了。

The problem is this line is not correct: 问题是此行不正确:

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

if you want to call the test method you should first of all create an instance of the object Weather : 如果要调用test方法,则应首先创建对象Weather的实例:

namespace App\Http\Controllers;

class TestController extends Controller {

    public function bla()
    {
        $w = new \App\Helpers\Weather();

        return $w->test();
    }
}

Instead, if you want to call the method directly on the class, you should make this method static: 相反,如果要直接在类上调用该方法,则应将此方法设为静态:

class Weather {

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

and call it this way: 并这样称呼:

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

In Laravel 5.0 and 5.1 you no longer need to run composer dump-autoload because the new PSR-4 takes care of that. 在Laravel 5.0和5.1中,您不再需要运行composer dump-autoload因为新的PSR-4会解决这一问题。

I think this is the proper way to do it: 我认为这是正确的做法:

In Weather.php - NB: File name should be Weather.php 在Weather.php中-注意:文件名应为Weather.php

<?php namespace App\Helpers

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

In TestController.php 在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();
    }
 }

I noticed that weather.php has a lowercase w which should be uppercase. 我注意到weather.php的小写字母w应该是大写字母。 Maybe that's the problem? 也许那是问题所在?

Your helper class should be added to autoload section composer.json . 您的帮助程序类应添加到autoload部分composer.json Like, 喜欢,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM