DEV Community

Cover image for 3 nices features on PHP8.0
Mbenga
Mbenga

Posted on

3 nices features on PHP8.0

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
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

But now you could just write :

$parent?->method();
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Since PHP 8.0, you can define your attributes directly in the constructor:

class Example{
  public function __construct(
    public float $attribute,
  ) {
  }
}
Enter fullscreen mode Exit fullscreen mode

Thank's for reading

Have a good day
Kisses

French version of this post just here :

Latest comments (0)