来自Treehouse blog:
在 PHP 7 中,我们现在添加了标量类型。具体来说:int、float、
字符串和布尔值。
通过添加标量类型提示并启用严格要求,它是
希望能有更多正确和自文档的 PHP 程序
书面。它还使您可以更好地控制您的代码,并且可以使
代码更容易阅读。
默认情况下,标量类型声明是非严格的,这意味着它们
将尝试更改原始类型以匹配指定的类型
通过类型声明。换句话说,如果你传递一个字符串
从一个数字开始到一个需要浮点数的函数中,它将
从头开始抓取号码并删除其他所有内容。通过
将浮点数放入需要 int 的函数将变为 int(1)。
默认情况下,如果可能,PHP 会将错误类型的值转换为预期的标量类型。例如,为期望字符串的参数提供整数的函数将获得字符串类型的变量。
已禁用严格类型 (eval):
<?php
function AddIntAndFloat(int $a, float $b) : int
{
return $a + $b;
}
echo AddIntAndFloat(1.4, '2');
/*
* without strict typing, PHP will change float(1.4) to int(1)
* and string('2') to float(2.0) and returns int(3)
*/
可以在每个文件的基础上启用严格模式。在严格模式下,只会接受类型声明的确切类型的变量,否则会抛出 TypeError。此规则的唯一例外是可以将整数提供给期望浮点数的函数。内部函数中的函数调用不受 strict_types 声明的影响。
要启用严格模式,请使用 declare 语句和 strict_types 声明:
已启用严格类型 (eval):
<?php declare(strict_types=1);
function AddIntAndFloat(int $a, float $b): int
{
return (string) $a + $b;
}
echo AddIntAndFloat(1.4,'2');
// Fatal error: Uncaught TypeError: Argument 1 passed to AddIntAndFloat() must be of the type int, float given
echo AddIntAndFloat(1,'2');
// Fatal error: Uncaught TypeError: Argument 2 passed to AddIntAndFloat() must be of the type float, string given
// Integers can be passed as float-points :
echo AddIntAndFloat(1,1);
// Fatal error: Uncaught TypeError: Return value of AddIntAndFloat() must be of the type integer, string returned
工作示例:
<?php
declare(strict_types=1);
function AddFloats(float $a, float $b) : float
{
return $a+$b;
}
$float = AddFloats(1.5,2.0); // Returns 3.5
function AddFloatsReturnInt(float $a, float $b) : int
{
return (int) $a+$b;
}
$int = AddFloatsReturnInt($float,1.5); // Returns 5
function Say(string $message): void // As in PHP 7.2
{
echo $message;
}
Say('Hello, World!'); // Prints "Hello, World!"
function ArrayToStdClass(array $array): stdClass
{
return (object) $array;
}
$object = ArrayToStdClass(['name' => 'azjezz','age' => 100]); // returns an stdClass
function StdClassToArray(stdClass $object): array
{
return (array) $object;
}
$array = StdClassToArray($object); // Returns array
function ArrayToObject(array $array): object // As of PHP 7.2
{
return new ArrayObject($array);
}
function ObjectToArray(ArrayObject $object): array
{
return $object->getArrayCopy();
}
var_dump( ObjectToArray( ArrayToObject( [1 => 'a' ] ) ) ); // array(1 => 'a');