Skip to main content

Devbit

Declaring the return parameter with NULLable type as an option.

Handling a situation where a function might return an error since it returns NULL.
/**
 * Retrieves the name of a role based on its ID.
 *
 * @param string $role_id
 *   The ID of the role to retrieve.
 *
 * @return string|null
 *   The name of the role if it exists, or NULL if the role is not found.
 */
public function getRoleName(string $role_id): ?string {
  // Example roles array.
  $roles = [
    'admin' => 'Administrator',
    'editor' => 'Content Editor',
    'viewer' => 'Viewer',
  ];

  // Use the null coalescing operator to return the role name or null.
  return $roles[$role_id] ?? NULL;
}

Issue:

Handling a situation where a function might return an error since it returns NULL.

Solution:

Utilizes the "?" in the definition of the return type.

PHP
Profilfoto Lothar Neumann

Lothar Ferreira Neumann

Junior Drupal Entwickler

Ihre Drupal-Website zukunftssicher machen

Wir prüfen Ihr System und zeigen, was Sie für AI, Wartung und Upgrades brauchen.