Php 简明教程

PHP - Type Hints

PHP 支持在函数定义中的变量、类中属性或实例变量的声明时使用“类型提示”。PHP 被广泛认为是一种弱类型语言。在 PHP 中,在给变量赋值之前无需声明其类型。

PHP supports using "type hints" at the time of declaring variables in the function definition and properties or instance variables in a class. PHP is widely regarded as a weakly typed language. In PHP, you need not declare the type of a variable before assigning it any value.

PHP 解析器尽可能地尝试将变量转换为兼容类型。因此,如果传递的值之一是数字的字符串表示,而第二个是数字变量,PHP 会将字符串变量转换为数字以执行加法运算。

The PHP parser tries to cast the variables into compatible type as far as possible. Hence, if one of values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation.

Example

请看以下示例:

Take a look at the following example −

<?php
   function addition($x, $y) {
      echo "First number: $x Second number: $y Addition: " . $x+$y;
   }
   $x="10";
   $y=20;
   addition($x, $y);
?>

它将生成以下 output

It will produce the following output

First number: 10 Second number: 20 Addition: 30

但是,如果上述示例中的 $x 是不包含有效数字表现形式的字符串,则会出现错误。

However, if $x in the above example is a string that doesn’t hold a valid numeric representation, then you would encounter an error.

<?php
   function addition($x, $y) {
      echo "First number: $x Second number: $y Addition: " . $x+$y;
   }
   $x="Hello";
   $y=20;
   addition($x, $y);
?>

它将生成以下 output

It will produce the following output

PHP Fatal error:  Uncaught TypeError: Unsupported operand types: string + int in hello.php:5

类型提示从 PHP 5.6 版本起受支持。这意味着您可以明确说明代码中声明变量的预期类型。PHP 允许您对函数参数、返回值和类属性进行类型提示。有了它,就可以编写更健壮的代码。

Type-hinting is supported from PHP 5.6 version onwards. It means you can explicitly state the expected type of a variable declared in your code. PHP allows you to type-hint function arguments, return values, and class properties. With this, it is possible to write more robust code.

让我们在上述程序的加法函数中结合类型提示 −

Let us incorporate type-hinting in the addition function in the above program −

function addition($x, $y) {
   echo "First number: $x Second number: $y Addition: " . $x+$y;
}

类型提示特性主要由 IDE(集成开发环境)用于提示用户在函数声明中使用的参数的预期类型。

The type-hinting feature is mostly used by IDEs (Integrated Development Environment) to prompt the user about the expected types of the parameters used in function declaration.

下图显示了 VS 代码编辑器在您键入时弹出的函数原型 −

The following figure shows the VS Code editor popping up the function prototype as you type −

php type hints 1

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

If the cursor hovers on the name of the function, the type declarations for the parameters and the return value are displayed −

php type hints 2

请注意,仅在变量声明中使用数据类型并不能防止引发不匹配的类型异常,因为 PHP 是一种动态类型语言。换句话说,$x="10" 和 $y=20 仍然会计算结果为 30,而 $x="Hello" 会使解析器引发错误。

Note that by merely using the data types in the variable declarations doesn’t prevent the unmatched type exception raised, as PHP is a dynamically typed language. In other words, $x="10" and $y=20 will still result in the addition as 30, where as $x="Hello" makes the parser raise the error.

strict_types

PHP 可以强制执行更严格的类型转换规则,这样就不会将“10”隐式转换为 10。这可以通过在 declare() 语句中将 strict_types 指令设置为 1 来强制执行。declare() 语句必须是 PHP 代码中的第一个语句,紧跟在“ <?php ”标签后面。

PHP can be made to impose stricter rules for type conversion, so that "10" is not implicitly converted to 10. This can be enforced by setting strict_types directive to 1 in a declare() statement. The declare() statement must be the first statement in the PHP code, just after the "<?php" tag.

Example

<?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);
?>

它将生成以下 output

It will produce the following output

First number: 10 Second number: 20 Addition: 30

现在,如果将 $x 设置为“10”,则不会发生隐式转换,从而导致以下错误 −

Now, if $x is set to "10", the implicit conversion wont take place, resulting in the following error −

PHP Fatal error:  Uncaught TypeError: addition(): Argument #1 ($x) must be of type int, string given

VS Code IDE 也指示出相同的影响错误 −

The VS Code IDE too indicates the error of the same effect −

php type hints 3

从 PHP 7 开始,类型提示支持已扩展到函数返回值,以防止意外的返回值。您可以通过在冒号 (:) 符号后添加预期类型,在参数列表后添加类型提示返回值。

From PHP 7 onwards with type-hinting support has been extended for function returns to prevent unexpected return values. You can type-hint return values by adding the intended type after the parameter list prefixed with a colon (:) symbol.

Example

让我们为上述加法函数的返回值添加一个类型提示 −

Let us add a type hint to the return value of the addition function above −

<?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 会在您运行之前指示原因。

Here too, if the function is found to return anything other than an integer, the IDE indicates the reason even before you run.

php type hints 4

Union Types

PHP 在其 8.0 版本中引入了联合类型。你现在可以为单个声明指定多个类型。这些数据类型由“ | ”符号分隔。

The PHP introduced union types with its version 8.0. You can now specify more than one type for a single declaration. The data types are separated by the "|" symbol.

Example

在下面的 addition() 函数定义中, $x$y 参数可以是 intfloat 类型。

In the definition of addition() function below, the $x and $y arguments can be of int or float type.

<?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;
?>

Type-hinting in Class

在 PHP 7.4 版本中,您可以从版本 7.4 开始在声明类属性和方法时使用类型提示。

In PHP, from version 7.4 onwards, you can use the type hints in declaration of class properties and methods.

Example

在以下示例中,类构造函数使用类型提示 −

In the following example, the class constructor uses type hints −

<?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();
?>

也可以在声明类属性时使用类型提示。

It is also possible to use type hints in the declaration of class properties.

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";
   }
}

程序开发中最常见的错误是 type errors 。类型提示功能有助于减少它们。

The most commonly encountered errors during program development are type errors. The type-hinting feature helps in reducing them.