在PHP中,数据类型可以分为以下几类:
标量类型(Scalar Types):
42。3.14。"Hello, World!"。true 或 false。复合类型(Compound Types):
array(1, 2, 3) 或 [1, 2, 3]。new MyClass()。特殊类型(Special Types):
$var = NULL;。伪类型(Pseudo Types):
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(callable $callback): void {
$callback();
}
// 其他类型
function neverReturn(): never {
throw new Exception("This function never returns");
}
?>
PHP 提供了多种函数来检查变量的类型,如 is_int(), is_float(), is_string(), is_array(), is_object(), is_null(), is_resource(), is_callable() 等。
<?php
if (is_int($integer)) {
echo "This is an integer.";
}
if (is_callable($callback)) {
echo "This is a callable.";
}
?>
PHP 是弱类型语言,允许隐式类型转换,但你也可以显式地进行类型转换:
<?php
$number = "123";
$integer = (int)$number; // 显式转换为整数
?>
这些是PHP中的主要数据类型及其使用方式。