PHP type hinting with visiblity

Viewed 24

What is protected inside 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. 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();
1 Answers

Its a short hand that introduced in PHP 8 named as Constructor Property Promotion

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 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:

class Point {
    public function __construct(
        public float $x = 0.0,
        public float $y = 0.0,
        public float $z = 0.0,
    ) {}
}
Related