Home >Backend Development >PHP Tutorial >What built-in data types do PHP functions return?

What built-in data types do PHP functions return?

WBOY
WBOYOriginal
2024-04-19 12:24:02388browse

PHP functions can return various built-in data types, including: 1. Integer; 2. Floating point number; 3. String; 4. Boolean value; 5. Array; 6. Object; 7. NULL.

PHP 函数返回哪些内置数据类型?

#What built-in data types do PHP functions return?

PHP functions can return various built-in data types, including:

  • Integer (int)
  • Floating point number (float)
  • String(string)
  • Boolean value(bool)
  • Array(array)
  • Object(object)
  • NULL

Practical Case

Suppose we have a function calculate_age(DOB) to calculate age based on a given date of birth. This function returns the age as an integer.

function calculate_age(string $DOB): int
{
    $dobDate = new DateTime($DOB);
    $todayDate = new DateTime('today');
    $age = $todayDate->diff($dobDate)->y;

    return $age;
}

Call this function:

$age = calculate_age('1980-01-01');
echo "Age: $age"; // 输出:Age: 43

Other examples

    ##
    function is_valid(string $email): bool
    {
      return filter_var($email, FILTER_VALIDATE_EMAIL);
    }
  • function get_products(): array
    {
      // 从数据库获取产品列表
      $productDetails = [
          ['id' => 1, 'name' => 'Product 1'],
          ['id' => 2, 'name' => 'Product 2']
      ];
    
      return $productDetails;
    }

The above is the detailed content of What built-in data types do PHP functions return?. 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