我可以将自定义 class 转换为 blade Laravel 中的变量吗
Can I cast a custom class to a variable in blade Laravel
我可以在 Laravel Blade:
中做类似的事情吗
@foreach($collection as (CustomClass) $object)
这是不可能的。由于 Blade 是一种 PHP 模板语言,你只能做 PHP 允许的事情......它不允许你对局部变量进行类型转换。
您只能在新发布的 PHP 7.4 - class 属性中键入提示函数参数和 -。你也可以给你的函数一个 return 类型。
PHP 7+:
public function foo(string $bar): int
{
return strlen($bar);
}
PHP 7.4+ :
protected int $count;
当然,我的示例是用标量类型(字符串、整数、浮点数、布尔值)制作的,但您完全可以在此处放置自定义 class。
public function logout(App\User $user)
{
//stuff
}
您可以使用 Collection::whereInstanceOf()
过滤掉您不想要的任何内容 class。
https://laravel.com/docs/5.8/collections#method-whereinstanceof
@foreach($collection->whereInstanceOf(CustomClass) as $object)
如果您想简单地排除不是您的内容的错误 class,那么您可以比较集合的大小。但我建议在控制器中进行:
if ($collection->whereInstanceOf(CustomClass)->count() !== $collection->count()) {
throw Exception();
}
您在问题中提供的信息很少,但由于您使用的是@foreach,因此您可以按照以下方式进行类型转换:
@foreach($collection as $object)
@php($object = (object)$object)
......
@endforeach
这应该允许您使用 $object->item
我可以在 Laravel Blade:
中做类似的事情吗@foreach($collection as (CustomClass) $object)
这是不可能的。由于 Blade 是一种 PHP 模板语言,你只能做 PHP 允许的事情......它不允许你对局部变量进行类型转换。
您只能在新发布的 PHP 7.4 - class 属性中键入提示函数参数和 -。你也可以给你的函数一个 return 类型。
PHP 7+:
public function foo(string $bar): int
{
return strlen($bar);
}
PHP 7.4+ :
protected int $count;
当然,我的示例是用标量类型(字符串、整数、浮点数、布尔值)制作的,但您完全可以在此处放置自定义 class。
public function logout(App\User $user)
{
//stuff
}
您可以使用 Collection::whereInstanceOf()
过滤掉您不想要的任何内容 class。
https://laravel.com/docs/5.8/collections#method-whereinstanceof
@foreach($collection->whereInstanceOf(CustomClass) as $object)
如果您想简单地排除不是您的内容的错误 class,那么您可以比较集合的大小。但我建议在控制器中进行:
if ($collection->whereInstanceOf(CustomClass)->count() !== $collection->count()) {
throw Exception();
}
您在问题中提供的信息很少,但由于您使用的是@foreach,因此您可以按照以下方式进行类型转换:
@foreach($collection as $object)
@php($object = (object)$object)
......
@endforeach
这应该允许您使用 $object->item