Php 简明教程

PHP - Strict Typing

PHP 通常被认为是一种弱类型语言。在 PHP 中,不需要在将值分配给变量之前声明变量的类型。PHP 解析器会尽力将变量转换为兼容的类型。

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. The PHP parser tries to cast the variables into compatible type as far as possible.

例如,如果传递的值之一是数字的字符串表示,而第二个是数字变量,PHP 会将字符串变量转换为数字来执行加法运算。

For example, if one of the 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 will 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

Type Hints

类型提示从 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(int $x, int $y) {
   echo "First number: $x Second number: $y Addition: " . $x+$y;
}

请注意,仅仅在变量声明中使用数据类型并不能防止出现不匹配的类型异常,因为 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, whereas $x="Hello" makes the parser raise the error.

Example

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

   $x=10;
   $y=20;
   addition($x, $y);

   $x="10";
   $y=20;
   addition($x, $y);

   $x="Hello";
   $y=20;
   addition($x, $y);
?>

它将生成以下 output

It will produce the following output

First number: 10
Second number: 20
Addition: 30

First number: 10
Second number: 20
Addition: 30

First number: Hello
Second number: 20
PHP Fatal error:  Uncaught TypeError: Unsupported operand
types: string + int in hello.php:5

strict_types

可以使 PHP 强制实施更严格的类型转换规则,这样就不会将“10”隐式转换为 10。这可以通过在 declare() 语句中将 strict_types 指令设置为 1 来强制执行。

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.

declare() 语句必须是 PHP 代码中的第一条语句,紧挨在“<?php”标签后面。

The declare() statement must be the first statement in the PHP code, just after the "<?php" tag.

Example

请看以下示例:

Take a look at the following 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”,则不会执行隐式强制转换,导致以下 error

Now, if $x is set to "10", the implicit conversion won’t take place, resulting in the following error

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

从 PHP 7 开始,已对函数返回类型提示支持进行了扩展以防止意外返回值。您可以在参数列表后添加带冒号 (:) 符号前缀的目标类型,从而对返回值进行类型提示。

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

Example

我们为以下 division() 函数的返回值添加类型提示。

Let us add a type hint to the return value of the division() function below.

<?php
   declare (strict_types=1);
   function division(int $x, int $y) : int {
      return $x/$y;
   }

   $x=10;
   $y=20;
   $result = division($x, $y);
   echo "First number: $x Second number: $y Addition: " . $result;
?>

因为该函数返回 0.5,而这并非 int 类型(也就是函数返回值所使用的类型提示),所以会显示以下 error

Because the function returns 0.5, which is not of int type (that is, the type hint used for the return value of the function), the following error is displayed −

Fatal error: Uncaught TypeError: division(): Return value must be
of type int, float returned in hello.php:5