严格类型在PHP中有什么作用? [英] What do strict types do in PHP?

查看:90
本文介绍了严格类型在PHP中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在PHP 7中看到了以下新行,但是没有人真正解释它的含义.我已经在Google上搜索了,他们谈论的只是您是否要启用它,而不是像民意调查这类的东西.

I've seen the following new line in PHP 7, but nobody really explains what it means. I've googled it and all they talk about is will you be enabling it or not like a poll type of thing.

declare(strict_types = 1);

它是做什么的?它如何影响我的代码?我应该这样做吗?

What does it do? How does it affect my code? Should I do it?

一些解释会很好.

推荐答案

来自树屋博客:

使用PHP 7,我们现在添加了标量类型.具体来说:int,float, 线和布尔.

With PHP 7 we now have added Scalar types. Specifically: int, float, string, and bool.

通过添加标量类型提示并启用严格的要求,它可以 希望可以编写更多正确且具有自文档说明的PHP程序 书面.它还使您可以更好地控制代码,并且可以使 代码更易于阅读.

By adding scalar type hints and enabling strict requirements, it is hoped that more correct and self-documenting PHP programs can be written. It also gives you more control over your code and can make the code easier to read.

默认情况下,标量类型声明是非严格的,这意味着它们 将尝试更改原始类型以匹配指定的类型 通过类型声明.换句话说,如果您传递一个字符串, 从一个数字开始到一个需要浮点数的函数中,它将 从头开始抓取数字,然后删除其他所有内容.通过 浮点到需要int的函数中的值将变为int(1).

By default, scalar type-declarations are non-strict, which means they will attempt to change the original type to match the type specified by the type-declaration. In other words, if you pass a string that starts with a number into a function that requires a float, it will grab the number from the beginning and remove everything else. Passing a float into a function that requires an int will become int(1).

默认情况下,PHP会尽可能将错误类型的值转换为预期的标量类型.例如,一个为期望字符串的参数提供整数的函数将获得字符串类型的变量.

By default, PHP will cast values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

禁用严格类型(评估):

<?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声明的影响.

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.

要启用严格模式,将define语句与strict_types声明一起使用:

To enable strict mode, the declare statement is used with the strict_types declaration:

启用了严格类型(评估):

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

这篇关于严格类型在PHP中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆