Php 无法从控制器调用trait中的方法
我试图使用trait在我的Laravel应用程序上处理图像上传,但是trait中的任何函数都不能从控制器调用。 它抛出一个BadMethodCallException,并表示找不到该函数 我尝试使用非常简单的函数来测试trait是否有问题,或者函数本身是否有问题,但即使是只包含Php 无法从控制器调用trait中的方法,php,laravel,traits,Php,Laravel,Traits,我试图使用trait在我的Laravel应用程序上处理图像上传,但是trait中的任何函数都不能从控制器调用。 它抛出一个BadMethodCallException,并表示找不到该函数 我尝试使用非常简单的函数来测试trait是否有问题,或者函数本身是否有问题,但即使是只包含 return "sampletext"; 也有同样的问题 特征路径位于App/Traits/UploadTrait下 我已经在我的控制器中检查了use语句的拼写,上面写着use-App\Traits\UploadTra
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();
...
当然,我希望调用trait中的函数,但这不会发生。您需要在控制器中使用trait,并在类函数中移动
$this->test()
:
<?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
关键字才能在类中使用该特性及其方法
trait UploadTrait
{
public function test(){
return "testtext";
}
}
class Controller{
}
class UserProfileController extends Controller
{
use UploadTrait;
}
$ob = new UserProfileController();
echo $ob->test();
您可以创建一个函数,并调用trait
函数
在类中使用trait,例如:
use my/path/abcTrait;
Class My class{
use abcTrait;
}
现在,您可以在函数中使用$this->functionName()
调用trait函数。您能告诉我们结构吗?在添加了use
的位置,以及调用$this->test()
的位置?完成。我已经添加了尽可能多的细节,但没有复制粘贴所有内容。我不敢相信我错过了。非常感谢。