Home > Backend Development > PHP8 > Explain the new features of PHP8 with examples

Explain the new features of PHP8 with examples

藏色散人
Release: 2023-02-17 12:24:01
forward
3561 people have browsed it

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);
Copy after login

Annotation function

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

Example:

#[Attribute]class PrintSomeThing{
  public function __construct($str = &#39;&#39;)
  {
     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’}
Copy after login

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
        ) {}
    }
Copy after login

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);
    }
Copy after login

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
Copy after login
##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调用,不报错,返回空
Copy after login
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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template