[英]PHP type hinting with visiblity
What is protected
inside protected Service $service
? protected
保护的protected Service $service
中受保护的内容是什么?
public function __construct(protected Service $service)
{
}
What this feature is called?这个功能叫什么?
If i use protected then i do not need to declare and initialize the $service.如果我使用受保护,那么我不需要声明和初始化$service。 how this is possible?
这怎么可能?
class Sample
{
public function __construct(protected Service $service)
{
}
public function process()
{
$this->service->test();
}
}
class Service
{
public function test()
{
echo "test";
}
}
$obj = new Sample(new Service());
$obj->process();
Its a short hand that introduced in PHP 8它是在 PHP 8 中引入的简写
Before: the definition of simple value objects requires a lot of boilerplate, because all properties need to be repeated at least four times.之前:简单值对象的定义需要大量的样板,因为所有的属性都需要至少重复四次。 Consider the following simple class:
考虑以下简单的 class:
class Point {
public float $x;
public float $y;
public float $z;
public function __construct(
float $x = 0.0,
float $y = 0.0,
float $z = 0.0,
) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
After : But now as PHP introduced Constructor Property Promotion a short hand syntax, which allows combining the definition of properties and the constructor:之后:但是现在 PHP 引入了Constructor Property Promotion一种简写语法,它允许结合属性的定义和构造函数:
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.