Home >Backend Development >PHP Tutorial >What are the different data types that PHP functions can return?

What are the different data types that PHP functions can return?

PHPz
PHPzOriginal
2024-04-11 09:06:01839browse

PHP functions can return various data types, including integers, floating point numbers, strings, Boolean values, arrays, objects, and NULL. Specific methods include: Returning integers: using int type hints and return statements; returning floating point numbers: using float type hints and return statements; returning strings: using string type hints and return statements; returning Boolean values: using bool type hints and return statements ; Return an array: use array type hints and return statements; return objects: create an object and return it; return NULL: use ? type hints and return statements.

PHP 函数可以返回哪些不同数据类型?

Data types returned by PHP functions

In PHP, functions can return various data types, including:

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

Practical case

Let’s see how to define different returns Data type function:

<?php

// 返回整数
function sum(int $a, int $b): int
{
    return $a + $b;
}

// 返回浮点数
function average(float $a, float $b): float
{
    return ($a + $b) / 2;
}

// 返回字符串
function greet(string $name): string
{
    return "Hello, $name!";
}

// 返回布尔值
function isOdd(int $number): bool
{
    return $number % 2 != 0;
}

// 返回数组
function getNames(): array
{
    return ["John", "Mary", "Bob"];
}

// 返回对象
class Person
{
    public $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
}
function createPerson(string $name): Person
{
    return new Person($name);
}

// 返回 NULL
function getOptionalData(): ?string
{
    // 根据某些条件返回数据或 NULL
    if (rand(0, 1)) {
        return "Data";
    }
    return null;
}

// 调用函数
$result1 = sum(1, 2); // 整数
$result2 = average(3.5, 5.5); // 浮点数
$result3 = greet("Alice"); // 字符串
$result4 = isOdd(7); // 布尔值
$result5 = getNames(); // 数组
$result6 = createPerson("Bob"); // 对象
$result7 = getOptionalData(); // NULL

// 打印结果类型
echo gettype($result1) . "\n";
echo gettype($result2) . "\n";
echo gettype($result3) . "\n";
echo gettype($result4) . "\n";
echo gettype($result5) . "\n";
echo gettype($result6) . "\n";
echo gettype($result7) . "\n";

?>

Output result:

integer
double
string
boolean
array
object
NULL

The above is the detailed content of What are the different data types that PHP functions can 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