从控制器 Laravel 中的助手访问 class

Access class from helper in controller Laravel

我创建了一个助手,并尝试在我的一个控制器中使用它,但出现错误,我不确定为什么。

//StringHelper.php
namespace App\Helpers;

class StringHelper
{
    public function example($str1){
        //CODE
    }
}


//config/app.php
'aliases' => [
    'StringHelper' => App\Helpers\StringHelper::class,
]


//In controller 
use StringHelper;

$percentage = StringHelper::example($title);

Non-static method App\Helpers\StringHelper::example() should not be called statically

因为方法example($str1)不是静态的,需要实例调用

我认为你在example中调用了其他实例的方法,所以简单的方法是通过实例调用方法。

$helper = new StringHelper();
$percentage = $helper->example($title);

或者您需要将所有这些方法定义为静态的。