【发布时间】:2017-07-10 05:53:17
【问题描述】:
我刚刚阅读了this post 以创建一个可以从任何控制器访问的全局函数。但我不明白它是如何工作的。
我想让任何控制器都可以访问变量“服务”。所以,我把General.php 放到app/Http 中。这是代码。
<?php
class General {
public function getServices() {
$services = "SELECT * FROM products";
return $services;
}
}
我在控制器中包含它
<?php
namespace App\Http\Controllers;
use App\Http\General;
use Illuminate\Http\Request;
class HomeController extends Controller {
public function index() {
$title = 'Our services';
$services = General::getServices();
return view('welcome', compact('title','services'));
}
}
当我运行它时,我得到了错误Class 'App\Http\General' not found。然后我怎么能
任何人都可以提供帮助将不胜感激。
【问题讨论】:
-
您的代码中有 2 个错误:首先:您在通用类的顶部添加了正确的命名空间。第二:getServices() 方法必须声明为静态的,如果你想像 General::getServices() 一样使用它;