简体   繁体   中英

PHP type hinting with visiblity

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();

Its a short hand that introduced in 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 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,
    ) {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM