search
HomeBackend DevelopmentPHP8Explain the new features of PHP8 with examples

This article brings you a new characteristic interpretation and example of PHP8, I hope it will be helpful to friends in need!

Interpretation and examples of new features of PHP8.0

New named parameter function

What are named parameters?
is a named parameter. When calling a function, you can specify the parameter name. After specifying the parameter name, the parameter order can be passed in order without installing the original function parameters.

Example:

  <?php       /**
       * 计算余额方法
       * @param $amount 账户金额
       * @param $payment 支出金额
       * @return $balance = $amount-$payment 余额
       */
      function balance($amount, $payment)
      {
          return $amount - $payment;
      }
      //传统方式调用
      balance(100, 20);
      //php8 使用命名参数调用
      balance(amount: 100, payment: 20);
      //也可以换个顺序,这样来
      balance(payment: 20, amount: 100);

Annotation function

What are annotations? Go directly to the code, and finally explain

Example:

#[Attribute]class PrintSomeThing{
  public function __construct($str = '')
  {
     echo sprintf("打印字符串 %s \n", $str);
  }}#[PrintSomeThing("hello world")]class AnotherThing{}// 使用反射读取住解$reflectionClass = new ReflectionClass(AnotherThing::class);$attributes = $reflectionClass->getAttributes();foreach($attributes as $attribute) {
  $attribute->newInstance(); //获取注解实例的时候,会输出 ‘打印字符串 Hello world’}

Personal understanding summary of the annotation function. Using annotations can define classes into metadata with low decoupling and high cohesion. kind. It can be flexibly introduced through annotations when used, and the purpose of calling can be achieved when reflecting annotated class instances.
**The annotated class will only be called when it is instantiated

Constructor property promotion

What does it mean, it is that the modifier scope of class attributes can be declared in the constructor
Example:

<?php     // php8之前
    class User
    {
        protected string $name;
        protected int $age;
        public function __construct(string $name, int $age)
        {
            $this->name = $name;
            $this->age = $age;
        }
    }
    //php8写法,
    class User
    {
        public function __construct(
            protected string $name,
            protected int $age
        ) {}
    }

It saves the amount of code and does not need to declare class attributes separately.

Union type

In scenarios where the parameter type is uncertain, you can use it.

Example:

    function printSomeThing(string|int $value)
    {
        var_dump($value);
    }

Match expression

is similar to switch cash, but it is a strict === match

Example:

<?php $key = &#39;b&#39;;$str = match($key) {
    &#39;a&#39; => 'this a',
    'c' => 'this c',
     0  => 'this 0',
    'b' => 'last b',};echo $str;//输出 last b
##New Nullsafe operator

<?php    class User
   {
       public function __construct(private string $name)
       {
           //啥也不干
       }
       public function getName()
       {
           return $this->name;
       }
    }
    //不实例 User 类,设置为null
    $user = null;
   echo $user->getName();//php8之前调用,报错
   echo $user?->getName();//php8调用,不报错,返回空
Simplified is_null judgment

Recommended learning: "
PHP Video Tutorial"

The above is the detailed content of Explain the new features of PHP8 with examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)