I just want to share with you really cool feature off PHP 8.0
Named Argument
The use-case of this feature is when you want to use a function who has a lot of optional argument like this one:
function exampleFunction(
$param1,
$param2 = "param2",
$param3="param3",
$param4="param4")
{
# some actions
}
If you need to use this function with the default parameters, except the last one, you used to do something like:
exampleFunction($param1,"param2","param3","param4-v2");
That's long. Too long. But don't panic. With php8.0 You don't have to repeat all arguments anymore. You could just pass the required parameters, and the optional you want by naming them. That would look like this:
exampleFunction($param1,param4:"param4-v2");
Nullsafe operator
This time, we'll talk about objects. If you want to access to the methods of an object, you should check if the object is initialized. To do that,you would probably do something like:
if(isset($parent) && $parent!== null)
{
$parent->method();
}
But now you could just write :
$parent?->method();
That's particularly useful if you need to access a value by chaining methods. For example, in an MVC, if you want to access an attribute of the returned value of a fetch method of your model in your controller, you could write:
$this?->model??->fetch($id)?->name;
Simplification of writing class
If you write a class in PHP, you have to define your attributes and give them a security level. Formerly, that was done outside the __constructor. That means you can't assign value based on the __constructor's argument at the same time you defined that attributes.
class Example{
public float $attribute;
public function __construct(
float $attribute,
) {
$this->attribute = $attribute;
}
}
Since PHP 8.0, you can define your attributes directly in the constructor:
class Example{
public function __construct(
public float $attribute,
) {
}
}
Thank's for reading
Have a good day
Kisses
French version of this post just here :
Top comments (0)