在 laravel 10 网站上,我有一个定义了 getModelTitle 方法的特质
<?php
namespace App\Library\Traits;
trait AppCommonTrait
{
protected function getModelTitle(string $dataType): string
{
$a = \Str::of($dataType)->explode('\\');
return ((count($a) === 3)) ? $a[2] : '';
}
但是我未能从静态 app/Data/DataObjectUser.php 类中调用它:
use App\Models\Post;
use Spatie\LaravelData\Data;
class DataObjectUser extends Data // extends spatie/laravel-data package
{
use AppCommonTrait;
public function __construct() {
...
}
public static function getFilteredData(bool $returnJson = false, bool $extendResource = false): array
{
return self::$dataRows;
}
public static function filter(): bool
{
$model = self::getModelTitle(Post::class);
我有错误:
Non-static method App\Data\DataObjectUser::getModelTitle() cannot be called statically
Object DataObjectUser 静态调用,不知道是否有办法调用traite 方法?
"laravel/framework": "^10.48.7",
"spatie/laravel-data": "^4.4.1",
提前致谢!
只需将
protected function getModelTitle()
本身更改为静态,因为就像错误表明您无法从静态函数调用非静态函数
protected static function getModelTitle(string $dataType): string
{
$a = \Str::of($dataType)->explode('\\');
return ((count($a) === 3)) ? $a[2] : '';
}