Menu Home

PHP 8.2 : Union Types

PHP 8.2 introduces a new feature called union types, which allows developers to specify multiple types for a single variable. This can be useful in cases where a variable may hold different types of data at different points in the code.

For example, consider the following code:

Copy codefunction get_username(int $user_id) : string {
  // code to retrieve username from database
  return $username;
}

$username = get_username(123);

In this case, we are expecting the get_username function to return a string containing the username of the user with the given ID. However, if the ID is not found in the database, the function may return null instead. To account for this possibility, we can use union types to specify that the return type of the function can be either a string or null. The revised function would look like this:

Copy codefunction get_username(int $user_id) : ?string {
  // code to retrieve username from database
  return $username;
}

Now, the function is explicitly telling the PHP interpreter that it may return either a string or null, and the interpreter will not throw an error if null is returned.

Union types can also be used in function arguments. For example, consider the following code:

Copy codefunction log_message(string | array $message) {
  // code to log message to a file
}

log_message("Error occurred");
log_message(["Error", "File not found"]);

In this case, the log_message function is expecting either a string or an array as its argument. This allows the function to handle different types of messages without requiring multiple versions of the function for each type.

Overall, union types provide a convenient way for developers to specify multiple types for a single variable, making it easier to ensure that data is being passed correctly throughout the code.

Categories: PHP

Tagged as:

gunnard

Leave a Reply

Your email address will not be published. Required fields are marked *