PHP 支持在函数定义中声明变量时使用“类型提示”,而 class. PHP 中的属性或实例变量被广泛认为是一种弱类型语言。在 PHP 中,在为变量分配任何值之前,你不需要声明变量的类型。
PHP 解析器尝试尽可能将变量转换为兼容的类型。因此,如果传递的值之一是一个数字的字符串表示,而另一个是数字变量,PHP 会将 字符串变量 转换为 数字变量 以执行加法运算。
例
请看下面的例子 -
<?php
function addition($x, $y) {
echo "First number: $x Second number: $y Addition: " . $x+$y;
}
$x="10";
$y=20;
addition($x, $y);
?>
它将产生以下输出 -
但是,如果上例中的 $x 是一个不包含有效数字表示形式的字符串,则会遇到错误。
<?php
function addition($x, $y) {
echo "First number: $x Second number: $y Addition: " . $x+$y;
}
$x="Hello";
$y=20;
addition($x, $y);
?>
它将产生以下输出 -
从 PHP 5.6 版本开始支持类型提示。这意味着您可以显式声明代码中声明的变量的预期类型。PHP 允许你对函数参数、返回值和类属性进行类型提示。这样,就可以编写更健壮的代码。
让我们在上面程序的加法函数中加入类型提示 -
function addition($x, $y) {
echo "First number: $x Second number: $y Addition: " . $x+$y;
}
类型提示功能主要由 IDE(集成开发环境)用于提示用户函数声明中使用的参数的预期类型。
下图显示了在您键入时弹出函数原型的 VS Code 编辑器 -

如果光标悬停在函数名称上,则会显示参数的类型声明和返回值 -

请注意,仅在变量声明中使用数据类型并不能防止引发不匹配的类型异常,因为 PHP 是一种动态类型语言。换句话说,$x=“10” 和 $y=20 仍将导致加法为 30,而 as $x=“Hello” 会使解析器引发错误。
strict_types
可以使 PHP 对类型转换施加更严格的规则,以便 “10” 不会隐式转换为 10。这可以通过在 declare() 语句中将 strict_types 命令设置为 1 来强制执行。declare() 语句必须是 PHP 代码中紧跟在 “<?php” 标签之后的第一条语句。
例
<?php
declare (strict_types=1);
function addition(int $x, int $y) {
echo "First number: $x Second number: $y Addition: " . $x+$y;
}
$x=10;
$y=20;
addition($x, $y);
?>
它将产生以下输出 -
现在,如果 $x 设置为 “10”,则不会进行隐式转换,从而导致以下错误 -
VS Code IDE 也指示相同效果的错误 -

从 PHP 7 开始,类型提示支持扩展了函数返回,以防止意外的返回值。您可以通过在以冒号 (:) 符号为前缀的参数列表后添加预期类型来键入提示返回值。
例
让我们向上面的加法函数的返回值添加一个类型提示 -
<?php
declare (strict_types=1);
function addition(int $x, int $y) : int {
return $x+$y;
}
$x=10;
$y=20;
$result = addition($x, $y);
echo "First number: $x Second number: $y Addition: " . $result;
?>
同样,如果发现该函数返回整数以外的任何内容,IDE 甚至会在您运行之前指示原因。

联合类型
PHP 在其 8.0 版中引入了联合类型。现在,您可以为单个声明指定多个类型。数据类型由 “|” 符号分隔。
例
在下面的 addition() 函数定义中,$x 和 $y 参数可以是 int 或 float 类型。
<?php
declare (strict_types=1);
function addition(int|float $x, int|float $y) : float {
return $x+$y;
}
$x=10.55;
$y=20;
$result = addition($x, $y);
echo "First number: $x Second number: $y Addition: " . $result;
?>
类的类型提示
在 PHP 中,从 7.4 版本开始,您可以在类属性和方法的声明中使用类型提示。
例在下面的示例中,类构造函数使用类型提示 -
<?php
declare (strict_types=1);
class Student {
public $name;
public $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function dispStudent() {
echo "Name: $this->name Age: $this->age";
}
}
$s1 = new Student("Amar", 21);
$s1->dispStudent();
?>
也可以在类属性的声明中使用类型提示。
class Student {
public string $name;
public int $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function dispStudent() {
echo "Name: $this->name Age: $this->age";
}
}
程序开发过程中最常见的错误是类型错误。类型提示功能有助于减少它们。