在 PHP 中,数据类型可以分为以下几类:
42
。3.14
。"Hello, World!"
。true
和 false
。[1, 2, 3]
或 ["name" => "John", "age" => 30]
。new stdClass()
。null
。这些类型在文档中使用,用于描述函数参数或返回值的预期类型: - mixed:表示可以是任何类型。 - number:表示整数或浮点数。 - callback:表示回调函数。 - array|object:表示可以是数组或对象。 - void:表示函数没有返回值。
Traversable
接口的对象。<?php
// 标量类型
$integer = 42;
$float = 3.14;
$string = "Hello, World!";
$boolean = true;
// 复合类型
$array = [1, 2, 3];
$object = new stdClass();
// 特殊类型
$null = null;
$resource = fopen('file.txt', 'r');
// 伪类型
function exampleFunction(mixed $param): void {
// 函数体
}
// 迭代器
function iterate(iterable $iterable) {
foreach ($iterable as $item) {
echo $item . "\n";
}
}
// 可调用
$callable = function() {
echo "Called!";
};
$callable();
?>
PHP 提供了丰富的数据类型来满足不同的编程需求。理解这些数据类型及其用途对于编写高效、可维护的 PHP 代码至关重要。