Home  >  Article  >  Backend Development  >  How to use PHP8’s attribute nullability to improve code quality

How to use PHP8’s attribute nullability to improve code quality

王林
王林Original
2023-06-21 11:02:561497browse

With the release of PHP8, attribute nullability has become an important new feature. This feature allows us to declare that a property can be nullable, giving us more control over our code and helping us reduce some potential errors.

What is attribute nullability?

Before PHP, we could only declare properties as fixed types (such as strings, integers, Boolean, etc.). However, in some cases, properties may not be initialized or assigned a null value. This means that when calling these properties, we may encounter a fatal error, such as an undefined variable or the inability to call an undefined method.

Attribute nullability is achieved by adding a question mark in front of the attribute declaration. For example, we can declare a nullable string property as follows:

public ?string $name;

This means that we can set this property to NULL instead of a string, thus avoiding a fatal error.

How to use attribute nullability to improve code quality?

Using attribute nullability can greatly improve code quality. Here are some examples:

  1. Using attribute nullability in methods

For example, We have a Person class with a name and an age property. We can use property nullability to make our code safe as shown below:

class Person {
    public ?string $name;
    public ?int $age;
    
    public function displayInfo(): string {
        $name = $this->name ?? "Unknown";
        $age = $this->age ?? "Unknown";
        return "Name: $name, Age: $age";
    }
}

In the above example, we have used the null coalescing operator (??) to provide a default for undefined properties value. This means that even if the property is NULL, our code will not get a fatal error.

  1. Check if a property is empty

In some cases, we want to check if a property is empty. For example, if we use a blank string as the default value, we may want to prevent the user from passing an empty string. We can achieve this using property nullability as shown below:

class User {
    public ?string $name;
    
    public function setName(?string $name): void {
        if ($name === "") {
            throw new InvalidArgumentException("Name can't be empty");
        }
        $this->name = $name;
    }
}

In the above example, we used a nullable $name property of type NULL or String. In the setName method, we first check if $name is a blank string, and if so, throw an exception. Otherwise, we assign the value to the attribute.

  1. Dereferencing a nullable property

In some cases, we may want to convert a nullable property to a non-nullable property. For example, we might have an associative array that contains the same keys as object properties. We can use property nullability to convert these values ​​into object properties as shown below:

class Post {
    public ?string $title;
    public ?string $content;
    
    public function __construct(array $data) {
        $this->title = $data['title'] ?? null;
        $this->content = $data['content'] ?? null;
    }
    
    public function toObject(): object {
        $obj = (object)[];
        foreach ($this as $key => $value) {
            $obj->{$key} = &$this->{$key};
        }
        return $obj;
    }
}

$data = [
    'title' => 'Hello',
    'content' => 'World',
];
$post = new Post($data);
$obj = $post->toObject();

In the above example, we have used property nullability to simplify the code. In the constructor, we iterate over the associative array and assign the value to the nullable property (if the key does not exist, the value will be NULL). In the toObject method, we converted the object to an object and removed the nullability, making the property a non-null property.

Summary

Attribute nullability is a very useful feature that can greatly improve the quality of our code. It can help us avoid some common mistakes, such as avoiding using undefined variables or methods, and can help us have better control over our code. If you haven't upgraded to PHP8 yet, consider using this feature to improve the quality of your code.

The above is the detailed content of How to use PHP8’s attribute nullability to improve code quality. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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