Image

php

PHP 8

New features for PHP 8.0

1 min read
Last update: November 28, 2021
<?php

class Product
{
    private float|int $price;
    
    /**
     *  @param int|float $price
     */
    public function setPrice(int|float $price)
    {
        $this->price = $price
    }
}
<?php

class Product
{
    public function __construct(
        private float $price = 0.0,
    ) {}
}
<?php

class PostsController
{
    #[Route("/api/posts/{id}", methods: ["GET"])]
    public function get($id) { /* ... */ }
}
<?php

function my_method($text, $another_specific_option = true, $specific_option = true)
{
    // ...
}

my_method('specific text', specific_option: false);
<?php

$fn1 = fn($x) => $x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
    return $x + $y;
};
<?php

$country = $session?->user?->getAddress()?->country;

<?php

echo match (8.0) {
  '8.0' => "Oh no!",
  8.0 => "This is what I expected",
};
//> This is what I expected