search
HomeBackend DevelopmentPHP8How to use PHP8's attribute nullability to improve code quality

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

Jun 21, 2023 am 11:02 AM
phpCode qualityProperty nullability

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

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

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.