Dav*_*vid 29 php traits laravel laravel-5.2
我是Traits的新手,但是我的函数中有很多重复的代码,我想使用Traits来减少代码的混乱.我Traits在我的Http目录中创建了一个名为Trait的目录BrandsTrait.php.它所做的只是呼吁所有品牌.但是当我尝试在我的产品控制器中调用BrandsTrait时,如下所示:
use App\Http\Traits\BrandsTrait;
class ProductsController extends Controller {
use BrandsTrait;
public function addProduct() {
//$brands = Brand::all();
$brands = $this->BrandsTrait();
return view('admin.product.add', compact('brands'));
}
}
Run Code Online (Sandbox Code Playgroud)
它给我一个错误,说方法[BrandsTrait]不存在.我想初始化一些东西,或者用不同的方式称呼它?
这是我的 BrandsTrait.php
<?php
namespace App\Http\Traits;
use App\Brand;
trait BrandsTrait {
public function brandsAll() {
// Get all the brands from the Brands Table.
Brand::all();
}
}
Run Code Online (Sandbox Code Playgroud)
Sco*_*pey 37
考虑一下这样的特征,比如在不同的地方定义一个类的一部分,可以由许多类共享.通过use BrandsTrait在课堂上放置它有该部分.
你想写的是
$brands = $this->brandsAll();
Run Code Online (Sandbox Code Playgroud)
这是特征中方法的名称.
另外 - 不要忘记为您的brandsAll方法添加一个返回!
| 归档时间: |
|
| 查看次数: |
28482 次 |
| 最近记录: |