[英]Laravel 5 can't reach custom class function
我有一个关于Laravel 5的问题。我在app目录中创建了一个新目录和文件。
App
Helpers
weather.php
Http
Controllers
test.php
我想访问weather.php中的函数,但是不起作用。
Weather.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();
}
}
我收到一个找不到该类的错误。 希望有人可以帮助我,因为我不知道怎么了。
问题是此行不正确:
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();
}
在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();
}
}
我注意到weather.php
的小写字母w应该是大写字母。 也许那是问题所在?
您的帮助程序类应添加到autoload
部分composer.json
。 喜欢,
autoload": {
"files": [
"app/Http/Helpers/weather.php"
]
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.