Home Backend Development PHP Tutorial PHP : Top Features and Improvements

PHP : Top Features and Improvements

Jan 04, 2025 pm 07:44 PM

PHP 8.4 is finally here, bringing exciting changes that are set to transform the way developers work! With every new version, PHP keeps proving why it’s such an essential tool in today’s web development landscape.

Prerequisites

This article assumes you have basic knowledge of the PHP programming language.

Software I Use for PHP Development

  • Laravel Herd: used to manage my PHP versions and Nginx server.

  • PHPStorm: A great IDE with good IntelliSense and AI copilot.

  • Laragon: An easy-to-use local development environment that supports PHP and other technologies.


Asymmetric Property Visibility (version 2)??

In PHP, the visibility of object properties has traditionally been symmetric. This means that the ⁣get and set operations for a property must share the same visibility—public, private, or protected—but cannot differ.

For instance, if a property is public, both reading and writing to it are public, with no way to allow one operation without the other.

In context, when you declare a property of a class public, it becomes mutable, allowing it to be read and modified from outside the class.

However, with the advent of asymmetric visibility, you can now define separate scopes for reading and writing properties.

This means a property can be readable in one context and writable in another, offering greater control over how properties are accessed and modified.

class Animal{
  public private(set) string $name;

  public setName(string $foo){
    $ths->name = $foo;
  }
}

$animal = new Animal();

echo $animal->name; // This will run correctly
Copy after login
Copy after login
Copy after login

We can have a property made public and the set property is made private. This means the property cannot be updated outside the class, making it immutable.

If you try to modify the $name property, you will get an error showing that you cannot modify the property because of the visibility scope.

PHP : Top Features and Improvements

Here are a few key points to note about asymmetric visibility:

  • Spaces are not allowed in the set-visibility declaration. private(set) is correct. private( set ) is not correct and will result in a parse error.

  • If a property is declared as public, the main visibility can be omitted. For instance, public private(set) and private(set) will behave identically, as the public visibility is implied.

  • Only typed properties are allowed to have separate visibility for set operations. This means you cannot apply asymmetric visibility to untyped properties in PHP.

  • The set visibility must be the same as or more restrictive than the get visibility. For example, public protected(set) and protected protected(set) are valid, but protected public(set) will result in a syntax error.

Find out more about asymmetry visibility, including other examples for your perusal.

Property hooks ?

Property hook is a great feature of PHP 8.4 that introduces a way for developers to add get and set directives directly to a variable without expressively creating methods to read and write to the variable.

Alternatively,__get and __set magic methods can be used, but this makes the code more verbose, can introduce errors, and breaks static analysis tools.

It is safe to say the design and syntax of property hooks is similar to that of Kotlin but is mostly influenced by C# and Swift programming languages.

In PHP 8.3, we can create a class with a property in its constructor, and it gives us the capability to read and write to the property.

class Animal{
  public private(set) string $name;

  public setName(string $foo){
    $ths->name = $foo;
  }
}

$animal = new Animal();

echo $animal->name; // This will run correctly
Copy after login
Copy after login
Copy after login

The problem with this approach is that when we decide to write to the property, we either use the __set magic method or expressively create a method to mutate the variable, which might cause a break in the codebase down the line.

Property hooks allow developers to immediately create a set directive after creating the property.

class Car {
    public function __construct(public string $model) { }
}
Copy after login
Copy after login

Note that the value passed to the set directive must be the same type as the property, or else an error will be thrown.

You can pass another type to the set directive and convert it to the correct type before writing to the property, as seen below:

class Car{
  public string $model{
    set (string $value) {
      if(strlen($value) === 0){
        throw new ValueError("Model name cannot be empty");
      }
      $this->model = $value;
    }
  }
}
Copy after login
Copy after login

The example above shows how we can safely receive a compound type variable from the set directive and parse it to the correct type defined by the property.

You can omit the argument passed to the set directive if it is the same as the property type. For example, the two methods below are valid and behave similarly.

class Car{
  public string $year{
    set (string|number $value) {
      $year = intval($value);
      if($year < 2000){
        throw new ValueError("We only accept cars produced in year 2000 and above");
      }
      $this->year= $value;
    }
  }
}
Copy after login
Copy after login

Note that the argument defaults to $value if it is omitted. This syntax is common in programming languages like Kotlin and C#.

Instantiating Classes Without Extra Parentheses

Before this feature, accessing members of a class in PHP involved adding extra parentheses around the class.

// --------------------------METHOD 1----------------------------
public string $model{
    set (string $value) {
      if(strlen($value) === 0){
        throw new ValueError("Model name cannot be empty");
      }
      $this->model = $value;
    }
 }

// --------------------------METHOD 2----------------------------
public string $model{
    set {
      if(strlen($value) === 0){
        throw new ValueError("Model name cannot be empty");
      }
      $this->model = $value;
    }
  }
Copy after login

If you do not wrap the new Car() call in parentheses, you will get a parse error.

The new syntax allows us to access methods, properties, and constants without the need for extra parentheses.

class Car {

  public function getName(){
    return "Toyota Camry";
  }
}

$carName = (new Car())->getName();
Copy after login

For a full breakdown of this proposed change, check out the details in the RFC.

Introducing New Array Functions

New helper functions are coming to PHP 8.4.

Some of these functions already have their implementation in Laravel Arr or Collection helpers.

The array_find_key() Function

The array_find_key($array, $callback) function returns the key of the first element for which the $callback method returns true. If no element meets the condition, the function returns null.

class Animal{
  public private(set) string $name;

  public setName(string $foo){
    $ths->name = $foo;
  }
}

$animal = new Animal();

echo $animal->name; // This will run correctly
Copy after login
Copy after login
Copy after login

The array_find() Function

The array_find_key() function is designed to search through an array and return the key of the first element that satisfies a condition defined by a callback function.

Similarly to the array_find_key(), it returns null if no matching element is found.

class Car {
    public function __construct(public string $model) { }
}
Copy after login
Copy after login

If no fruit in the array had a quantity greater than 10, the function would return null.

The array_any() Function

The array_any() function determines if at least one element within an array fulfills a specific criterion specified by a provided evaluation function.

If at least one element meets the condition, the function returns true; otherwise, it returns false.

class Car{
  public string $model{
    set (string $value) {
      if(strlen($value) === 0){
        throw new ValueError("Model name cannot be empty");
      }
      $this->model = $value;
    }
  }
}
Copy after login
Copy after login

If no number in the array is greater than 10, the function will return false.

The array_all() Function

The array_all() function checks if every single item in an array passes a specific test. It applies a special rule (the callback function) to each item.

If all items pass the test according to the rule, then array_all() returns true.

class Car{
  public string $year{
    set (string|number $value) {
      $year = intval($value);
      if($year < 2000){
        throw new ValueError("We only accept cars produced in year 2000 and above");
      }
      $this->year= $value;
    }
  }
}
Copy after login
Copy after login

In this example, the array_all() function will iterate through the $numbers array and apply the callback function to each element. The callback checks if the number is divisible by 2 (i.e., even).

Since all numbers in the array are even, the array_all() function will return true, and the message "All numbers are even." will be displayed.


We’ve examined the key improvements introduced in PHP 8.4. These updates offer valuable enhancements for developers, including powerful new features and potential gains in efficiency.

To dive deeper into all the updates, including examples and detailed explanations, visit the official PHP 8.4.0 Release Announcement page.

Don’t forget to review the deprecations and backward compatibility changes to ensure a smooth transition to the latest version.

What’s Next? ?

  • If you enjoyed the article, don’t forget to share it with others.

  • I’d love to hear your thoughts—drop a comment below and let’s keep the conversation going. Cheers! ?

Follow me for more PHP, Node.js, TypeScript, and PHP articles! You can also find me on Twitter or LinkedIn.

The above is the detailed content of PHP : Top Features and Improvements. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

See all articles