Laravel 9突变器结肠
在Laravel 9中,突变器有不同的实现。以下示例来自官方文档。
protected function firstName(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst($value),
set: fn ($value) => strtolower($value),
);
}
但是, colon是什么: get
和set
是什么?这是PHP 8中的新功能吗?属性的定义:: make是:
public static function make(callable $get = null, callable $set = null): Attribute
In Laravel 9, there’s a different implementation for mutators. The following example is from the official documentation.
protected function firstName(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst($value),
set: fn ($value) => strtolower($value),
);
}
But what is the colon: after get
and set
? Is this a new feature in PHP 8? The definition of Attribute::make is:
public static function make(callable $get = null, callable $set = null): Attribute
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
new noreferrer”> new norguments 是PHP中的一个新功能8.0。
在具有简单签名的功能或方法中,它可以用作一种自我文献来指示参数是什么。例如,在您提供的代码中,两个参数都是简单的回调,可以对提供的值执行基本字符串操纵。没有参数名称,阅读代码的人将需要检查方法签名以了解每个参数的作用。
这也是仅在使用具有长签名或复杂默认值的函数或方法时指定所需参数的便捷方法。
例如,
htmlspecialchars()
的签名看起来像:在以前的版本中,如果您想将
double_encode
参数更改为false,但将其他参数作为默认,您,您'd必须这样做:除了更加混乱之外,我们还拥有非直觉的值,例如
null
和false
。过去,一种典型的方法是将变量用于诸如$ is_double_encoded = false
之类的值。但是借助命名参数,它看起来像这样:我们不仅跳过了保持其默认值的参数,而且
double_encode
参数清楚地标有其名称,我们可以从中推断出其用法。Named arguments are a new feature in PHP 8.0.
In functions or methods with simple signatures it can serve as a sort of self-documentation to indicate what the arguments are. For example in the code you provided, both arguments are simple callbacks that perform basic string manipulation on the provided value. Without the argument names, someone reading the code would need to check the method signature to know what each argument does.
It’s also a convenient way to only specify needed arguments when using functions or methods with long signatures or complex default values.
For example, the signature for
htmlspecialchars()
looks like this:In previous versions if you wanted to change the
double_encode
argument to false, but leave the other arguments as default, you’d have to do this:In addition to being more cluttered, we're left with non-intuitive values like
null
andfalse
. A typical approach in the past was to use variables for the values such as$is_double_encoded = false
. But with named arguments it looks like this:Not only do we skip the parameters which keep their default value, but the
double_encode
parameter is clearly labelled with its name, from which we can infer its usage.