Php 简明教程
PHP - Scalar Type Declarations
提供类型提示的功能自 5.0 版本起已内置于 PHP 中。 Type hinting 指在函数定义中提供参数数据类型的方法。在 PHP 7 之前,在函数中只能对数组、可调用和类使用类型提示。从 PHP 7 起,您还可以对标量数据类型(如 int、string、bool 等)的参数插入类型提示。
The feature of providing type hints has been in PHP since version 5. Type hinting refers to the practice of providing the data type of a parameter in the function definition. Before PHP 7, it was possible to use only the array, callable, and class for type hints in a function. PHP 7 onwards, you can also insert type hints for parameters of scalar data type such as int, string, bool, etc.
PHP 是一种动态(且弱)类型语言。因此,在定义函数时不需要声明参数类型,这是静态类型语言(如 C 或 Java)所必需的。
PHP is a dynamically (and weakly) typed language. Hence, you don’t need to declare the type of the parameter when a function is defined, something which is necessary in a statically type language like C or Java.
PHP 中函数的典型定义如下 −
A typical definition of function in PHP is as follows −
function addition($x, $y) {
echo "First number: $x Second number: $y Addition: " . $x+$y;
}
在此,我们假设参数 $x 和 $y 是数字的。但是,即使传递给函数的值不是数字,PHP 解析器仍会尽最大程度地尝试将变量强制转换为兼容的类型。
Here, we assume that the parameters $x and $y are numeric. However, even if the values passed to the function aren’t numeric, the PHP parser tries to cast the variables into compatible type as far as possible.
如果传递的值之一是数字的字符串表示,而第二个是数字变量,PHP 会将字符串变量强制转换为数字以执行加法操作。
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 this following example −
<?php
function addition($x, $y) {
echo "First number: " . $x;
echo "\nSecond number: " . $y;
echo "\nAddition: " . $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, an error is encountered.
<?php
function addition($x, $y) {
echo "First number: " . $x;
echo "\nSecond number: " . $y;
echo "\nAddition: " . $x+$y;
}
$x="Hello";
$y=20;
addition($x, $y);
?>
运行此代码并查看它如何显示 error 。
Run this code and see how it shows an error.
Scalar Type Declarations in PHP 7
PHP 7 版本引入的一项新功能允许定义一个函数,其参数的数据类型可以在括号中指定。
A new feature introduced with PHP version 7 allows defining a function with parameters whose data type can be specified within the parenthesis.
PHP 7 引入了以下标量类型声明 −
PHP 7 has introduced the following Scalar type declarations −
-
Int
-
Float
-
Bool
-
String
-
Interfaces
-
Array
-
Callable
旧版本的 PHP 只允许使用数组、可调用和类类型作为类型提示。此外,在旧版本的 PHP(PHP 5)中,致命错误为可恢复错误,而新版本(PHP 7)返回可抛出错误。
Older versions of PHP allowed only the array, callable and class types to be used as type hints. Furthermore, in the older versions of PHP (PHP 5), the fatal error used to be a recoverable error while the new release (PHP 7) returns a throwable error.
标量类型声明以两种模式实现 −
Scalar type declaration is implemented in two modes −
-
Coercive Mode − Coercive is the default mode and need not to be specified.
-
Strict Mode − Strict mode has to be explicitly hinted.
Coercive Mode
前面示例中定义的 addition() 函数现在可以重新编写,方法是合并类型声明,如下所示:
The addition() function defined in the earlier example can now be re-written by incorporating the type declarations as follows −
function addition(int $x, int $y) {
echo "First number: $x Second number: $y Addition: " . $x+$y;
}
注意,如果字符串包含一个整数,解析器仍会将不兼容的类型(即字符串)强制转换为 int,就像以前一样。
Note that the parser still casts the incompatible types i.e., string to an int if the string contains an integer as earlier.
Example
请查看以下示例:
Take a look at this following example −
<?php
function addition(int $x, int $y) {
echo "First number: " . $x;
echo "\nSecond number: " . $y;
echo "\nAddition: " . $x+$y;
}
$x="10";
$y=20;
echo addition($x, $y);
?>
它将生成以下 output −
It will produce the following output −
First number: 10
Second number: 20
Addition: 30
很明显,这是因为 PHP 是一种弱类型语言,因为 PHP 尝试将字符串类型的变量强制转换为整数。PHP 7 引入了解决此问题的严格模式功能。
Obviously, this is because PHP is a weakly typed language, as PHP tries to coerce a variable of string type to an integer. PHP 7 has introduced a strict mode feature that addresses this issue.
Strict Mode
为了应对 PHP 的弱类型检查,已引入严格模式。此模式启用一个 declare statement −
To counter the weak type checking of PHP, a strict mode has been introduced. This mode is enabled with a declare statement −
declare (strict_types=1);
您应将此声明放在 PHP 脚本的开头(通常就在 PHP 标签的下方)。这意味着标量的类型严格程度是按文件配置的。
You should put this statement at the top of the PHP script (usually just below the PHP tag). This means that the strictness of typing for scalars is configured on a per-file basis.
在弱模式中,strict_types 标记为 0。将其设为 1 会强制 PHP 解析器检查传递的参数和值的兼容性。在以上代码中添加此声明并检查结果。它将显示以下错误信息:
In the weak mode, the strict_types flag is 0. Setting it to 1 forces the PHP parser to check the compatibility of the parameters and values passed. Add this statement in the above code and check the result. It will show the following error message −
Fatal error: Uncaught TypeError: addition():
Argument #1 ($x) must be of type int, string given,
called in add.php on line 12 and defined in add.php:4
Stack trace:
#0 add.php(12): addition('10', 20)
#1 {main}
thrown in add.php on line 4
Example
以下是函数定义中标量类型声明的另一个示例。启用严格模式后,如果将不兼容的类型作为参数传递,则会引发致命错误。
Here is another example of scalar type declaration in the function definition. The strict mode when enabled raises fatal error if the incompatible types are passed as parameters.
<?php
// Strict mode
// declare(strict_types = 1);
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
取消对该代码开头的 declare 声明的注释并运行它。现在,它将生成一个 error :
Uncomment the declare statement at the top of this code and run it. Now it will produce an error −
Fatal error: Uncaught TypeError:
sum(): Argument #2 must be of type int, string given,
called in add.php on line 9 and defined in add.php:4
Stack trace:
#0 add.php(9): sum(2, '3', 4.1)
#1 {main}
thrown in add.php on line 4
类型提示功能主要由 IDE 用于提示用户有关函数声明中使用的参数的预期类型的信息。以下屏幕截图显示了键入时 VS Code 编辑器弹出函数原型。
The type-hinting feature is mostly used by IDEs to prompt the user about the expected types of the parameters used in the function declaration. The following screenshot shows the VS Code editor popping up the function prototype as you type.