With the release of PHP 8, there are a number of new and powerful features that can help simplify and improve your codebase, so let's get right to it. These are in no particular order.
Named arguments
If you're like me, you may often forget the order of arguments to a function call. Well, no more! With PHP 8 we now have named arguments. A powerful feature that lets you specify function arguments by name instead of by order.
function square(num) {
return num * num;
}
echo square(2);
function square(num: num) {
return num * num;
}
echo square(num: 2);
</div>
Constructor property promotion
Constructor property promotion is a new way of defining properties of a class, it removes a lot of duplicate code by letting you define and initialize properties right in the constructor function.
class DB {
public function __construct(
public string $name = "";
public string table = "";
) {}
}
Union types
PHP 8 adds support for native union types, which lets you define multiple types for a single variable, hence, union types.
class DB {
public int|float $number;
public function __construct() {
}
}
Match expressions
Match expressions are a simpler alternative to the original switch expression. Compared to switch statements, matches are expressions and can therefore be stored in variables. Also, match expressions do a strict comparison.
echo match(8.0) {
"8.0" => "No match.",
8.0 => "Match"
};
** Sources **
Disclaimer: This blog post should not be interpreted as professional advice. I am not responsible for any actions taken based on this content and disclaim any liability for any resulting losses or damages.