使用PHP 7,我们现在添加了Scalar类型。具体来说:int,float,string和bool。
通过添加标量类型提示并启用严格要求,希望可以编写更正确且自我记录的PHP程序。它还使您可以更好地控制代码,并使代码更易于阅读。
默认情况下,标量类型声明是非严格的,这意味着它们将尝试更改原始类型以匹配type-declaration指定的类型。换句话说,如果将以数字开头的字符串传递给需要浮点数的函数,它将从头开始获取数字并删除其他所有数字。将float传递给需要int的函数将成为int(1)。
默认情况下,如果可能,PHP会将错误类型的值转换为预期的标量类型。例如,为需要字符串的参数赋予整数的函数将获得string类型的变量。
禁用严格类型(eval):
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):
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
工作实例:
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 on 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');