I decided to separate the five updates that I found to be the coolest and most useful in PHP 8.
1. Declaration of Variables in the Constructor:
Before:
class Customer {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
In PHP 8:
class Customer {
public function __construct(
private string $name,
private int $age
) {}
}
2. Named Arguments:
Before:
function calculatePrice(
$net = 0,
$raw = 0,
$taxes = 0
) {}
// to pass only the tax it would be necessary to do this
calculationPrice(
null,
null,
200
)
In PHP 8:
calculationPrice(taxes: 200);
3. Union Types:
function calculatePrice(
$liquid,
$gross,
$taxes
): int|float|null {}
function sum(
int|float $number1,
int|float $number2
) {}
4. Function str_contains()
:
$phrase = 'find me here';
echo str_contains($phrase, 'ache');
5. Optional chaining:
$object->getOtherObject()?->getValue();
I was excited about these updates, which will certainly make my daily life as a developer and that of others easier. It's great to see PHP always evolving! And you? Do you believe that PHP will die? What new thing did you like the most? Send it in the comments.
Top comments (0)