无法从控制器调用特征中的方法

Method in trait not able to be called from controller

我正在尝试使用特性来处理我的 Laravel 应用程序上的图像上传,但是我的特性中的 none 函数可以从控制器调用。 它抛出 BadMethodCallException 并表示找不到该函数。

我试过使用非常简单的函数来测试它是否是特征问题或者函数本身是否有问题,但即使是一个简单的 return 函数只包含

return "sampletext";

有同样的问题。

特征路径在App/Traits/UploadTrait下 我已经检查了控制器中 use 语句的拼写,上面写着 use App\Traits\UploadTrait;

namespace App\Traits;

trait UploadTrait
{
    public function test(){
        return "testtext";
    }
}

控制器有

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

use App\User;
use App\Profile;
use App\Traits\UploadTrait;

use Image;

class UserProfileController extends Controller
{
...
    protection function updateProfile($args, Request $request){
    ...
        return $this->test();
...

当然我希望我的特征中的函数被调用,但这并没有发生。

您需要在控制器中使用特征并将 $this->test() 移动到 class 函数中:

<?php

use App\Traits\UploadTrait;

class UserProfileController extends Controller
{
    use UploadTrait; // <-- Added this here

    public function index()
    {
        return $this->test(); // <-- Moved this into a function
    }
}

您必须输入 use 关键字才能在 class

中使用该特征及其方法
trait UploadTrait
{
  public function test(){
    return "testtext";
  }
}

class Controller{

}

class UserProfileController extends Controller
{
  use UploadTrait;

}

$ob = new UserProfileController();
echo $ob->test();

您可以创建一个函数并调用 trait 函数。

More Details

在 class 中使用 trait,例如:

use my/path/abcTrait;
Class My class{
      use abcTrait;
}

现在,您可以在函数中使用 $this->functionName () 调用特征函数。