>  기사  >  백엔드 개발  >  선언(strict_types=1)의 유효한 범위에 대해 이야기해 봅시다.

선언(strict_types=1)의 유효한 범위에 대해 이야기해 봅시다.

藏色散人
藏色散人앞으로
2022-01-30 04:00:326859검색

이 글에서는 선언(strict_types=1)의 유효 범위를 소개하겠습니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

declare(strict_types=1)

declare(strict_type=1);의 유효 범위에 대해서는 php7에 도입된 strict type 검사 모드의 지정된 구문입니다

Single 파일의 어디에 strict_types를 써야 하는지

기본 구문

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}

var_dump(add(1.0, 2.0));

이 상태에서 독립적으로 실행하는 경우 int(3)<를 출력합니다. /code ><code>严格类型检查模式的指定语法

单个文件时strict_types应写在哪里

基本语法

<?php
declare(strict_types=1);    //加入这句

function add(int $a, int $b): int
{
    return $a + $b;
}

var_dump(add(1.0, 2.0));

在此状态下执行独立时,输出int(3)

我们提供的是double类型,但php7能很好的处理它,和php5时代没什么区别

做了如下变更

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to add() must be of 
the type integer, float given, called in /Users/hiraku/sandbox/stricttypes/A.php on line 9 and defined in 
/Users/hiraku/sandbox/stricttypes/A.php:4
Stack trace:
#0 /Users/hiraku/sandbox/stricttypes/A.php(9): add(1, 2)
#1 {main}
  thrown in /Users/hiraku/sandbox/stricttypes/A.php on line 4

TypeError产生,如下

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}

declare(strict_types=1);

var_dump(add(1.0, 2.0));

strict_types不能写在脚本中间

declare语法不能写在脚本的中间,如下写法是错误的

PHP Fatal error:  strict_types declaration must be the very first statement in the script in 
/Users/hiraku/sandbox/stricttypes/A.php on line 7

产生如下错误

<?php
declare(strict_types=1) {
  //...
}

Fatal error产生,这甚至不是Throwable,而是编译过程中产生的错误

同样,与上述例子相似的位置,也不能使用如下语法

PHP Fatal error:  strict_types declaration must not use block mode in 
/Users/hiraku/sandbox/stricttypes/A.php on line 2
A.php脚本

<?php
declare(strict_types=1);
function add(int $a, int $b): int
{
    return $a + $b;
}

两个文件时strict_types如何产生作用

如下代码

A.php脚本在开头声明严格模式

B.php脚本

<?php
require &#39;A.php&#39;;
var_dump(add(1.0, 2.0));    //注意这里键入的是1.0和2.0浮点数,而A.php声明需要int

A.phpB.php文件require,如下

$ php B.php
int(3)

执行结果

A.php

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}

什么!!!!居然能够执行而不报错!!!!!
原来是B.php并没有声明strict_types,所以对于B脚本来说,是默认的松散模式

也就是说,对于strict_types有以下的行为

  • 不管怎么样,函数定义时的严格模式,行为并不会出现什么不同
  • 函数执行时的,严格模式会出现差异
  • declare(strict_types=1);的语法本身在A.php文件中完成,而被B.php文件require,而B.php并没有定义严格模式,那么执行require的文件(B.php)不会变成严格模式

上述解释就如如下代码所示,理论上A.php文件的严格模式已经关闭了,然而仅仅是B.php文件设定了declare(strict_types=1);,那么即使A.php没有设定严格模式,但A.phpB.php引用了,就对A.php使用严格模式

B.php

<?php
declare(strict_types=1);

require &#39;A.php&#39;;
var_dump(add(1.0, 2.0));
$ php B.php
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to add() 
must be of the type integer, float given, called in /Users/hiraku/sandbox/stricttypes/B.php on line 4 and 
defined in /Users/hiraku/sandbox/stricttypes/A.php:2
C.php

<?php
require_once &#39;B.php&#39;;
var_dump(add(1.0, 2.0));
var_dump(add2(1.0, 2.0));

三个文件时declare(strict_types=1);的作用

在函数定义部分使用declare(strict_types=1);

再增加一个require,试试3个文件嵌套

C.php → B.php → A.php
B.php

<?php
declare(strict_types=1);    //在函数定义部分声明
require_once &#39;A.php&#39;;
function add2($a, $b)
{
    return add($a, $b);
}
A.php

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}
$ php C.php 
int(3)
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given, called in 
/Users/hiraku/sandbox/stricttypes/B.php 
on line 7 and defined in /Users/hiraku/sandbox/stricttypes/A.php:2

执行结果如下

C.php

<?php
declare(strict_types=1);    //主体部分声明
require_once &#39;B.php&#39;;
var_dump(add2(1.0, 2.0));
  • var_dump(add(1.0, 2.0)); 能正确执行
  • var_dump(add2(1.0, 2.0));产生TypeError错误

也就是说,declare(strict_types=1);会按照如下方式变化

  • 定义函数本身的文件,并不能产生效果
  • 在定义的函数中调用其它函数,严格模式能产生效果(B.php使用了strict_types=1,同时B.php调用了A.php,所以A.php能起作用)

在主体部分中指定strict_types

不在B.php中途位置指定strict_types,而在主要部分即C.php指定,strict模式对所有的都有效吗?然而,事实上strict模式只有在引用的地方有效

C.php → B.php → A.php
B.php

<?php
require_once &#39;A.php&#39;;
function add2($a, $b)
{
    return add($a, $b);
}
A.php

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}
$ php C.php 
int(3)
Foo.php

<?php
// 这个文件的strict有效
declare(strict_types=1);

class Foo
{
    private $bar;

    public function __construct()
    {
        $this->bar = new Bar; // 执行严格模式
    }

    public function aaa()
    {
        $this->bar->aaa(); // 执行严格模式
    }
}
  • C.php中使用strict_types=1,因此add2(1.0,2.0)以严格模式执行,但是由于没有声明变量,所以没有任何效果
  • 另一方面,具有add2()定义的B.php处于非严格模式

总结

只有在写declare的文件的执行部分才会执行严格模式,该文件中调用的其它函数(其它文件中的函数)也会被影响

也就是说,哪个文件写了declare

우리가 제공하는 것은 double 유형이지만 php7은 이를 매우 잘 처리할 수 있으며 php5와 다르지 않습니다. code> era

다음과 같이 변경되었습니다

Bar.php

<?php
// 这个文件strict无效
class Bar
{
    private $moo;

    public function __construct()
    {
        $this->moo = new Moo; // 执行非严格模式
    }

    public function aaa()
    {
        $this->moo->aaa(); // 执行非严格模式
    }
}

TypeError가 발생했습니다. 다음과 같습니다

rrreee

strict_types를 작성할 수 없습니다. 스크립트 중간

declare 구문은 스크립트 중간에 작성할 수 없습니다. 다음 쓰기가 잘못되었습니다

rrreee

다음 오류가 발생합니다🎜rrreee

Throwable도 아닌 치명적 오류가 발생하는데, 컴파일 과정에서 발생한 오류입니다🎜

마찬가지로 다음 구문은 다음과 같은 위치에서는 사용할 수 없습니다. 위의 예🎜rrreeerrree

파일이 두 개인 경우 strict_types는 어떻습니까? 작동합니다

🎜다음 코드🎜🎜

A.php스크립트는 시작 부분에서 엄격 모드를 선언합니다🎜rrreee

A.php는 B.php 파일 require입니다. 다음과 같습니다🎜rrreee실행 결과🎜rrreee

🎜뭐야!!!! 에러 없이 실행이 가능하다!!!!!!🎜
B.php가 선언되지 않은 것으로 밝혀졌다 strict_types, 따라서 B 스크립트의 경우 기본 느슨한 모드입니다🎜

즉, strict_types의 경우 다음과 같은 동작을 합니다🎜

  • 상관없습니다 뭐, 함수가 정의되면 엄격 모드에서는 동작이 다르지 않습니다.
  • 🎜함수가 실행될 때 네, 엄격 모드에서는 차이가 있습니다 🎜
  • declare(strict_types=1); 구문 자체는 A.php 파일에서 완성되고 B.php 파일에서 require이고 B.php는 엄격 모드를 정의하지 않은 다음 require를 실행합니다. 파일(B.php)은 엄격 모드가 되지 않음

위의 설명은 다음 코드와 같습니다. 이론적으로 A.php 코드의 엄격 모드> 파일은 꺼졌습니다. 그러나 <code>B.php 파일에만 declare(strict_types=1);가 설정되어 있으므로 A.php 엄격 모드가 설정되지 않은 경우에도 하지만 A.phpB.php에 의해 참조되므로 A.php에는 엄격 모드를 사용하세요. 🎜rrreeerrreeerrreee

declare(strict_types=1); 세 개의 파일이 있는 경우

declare(strict_types=1);

다른 요구 사항을 추가하고 3개 파일을 중첩해 보세요🎜🎜C.php → B.php → A.phprrreeerrreeerrreee

실행 결과는 다음과 같습니다🎜rrreee

    var_dump(add(1.0, 2.0) ); 올바르게 실행될 수 있습니다.
  • var_dump(add2(1.0, 2.0));TypeError가 발생합니다.

즉 , declare(strict_types=1);는 다음과 같이 변경됩니다🎜

  • 함수 자체를 정의하는 파일은 아무런 효과를 내지 않습니다.
  • 정의된 함수, 엄격 모드는 효과를 생성할 수 있습니다(B.phpstrict_types=1를 사용하고 B .phpA.php, <code>A.php가 작동할 수 있음)

본문 부분 strict_types에 지정

중간에 strict_types를 지정하지 마세요 B.php인데 메인인 C.php에 명시해 놓는다. 엄격 모드는 모두 유효한가? 그런데 사실 엄격 모드는 인용된 곳에서만 유효하다🎜🎜 C.php → B.php → A.php rrreeerrreeerrreeerrreee

  • strict_types=1은 C.php에서 사용하므로 add2(1.0,2.0)은 strict 모드로 실행되지만 변수가 선언되지 않아 효과가 없습니다
  • 반면 add2() 정의가 있는 B.php는 non-strict 모드입니다.

요약

작성할 때만 declare

는 엄격 모드를 실행합니다. 파일에서 호출되는 다른 함수(다른 파일의 함수)도 영향을 받습니다.🎜

즉, 어떤 파일이 declare를 쓰는지, 모두 파일 안의 코드는 다른 파일에서 온 코드라도 검사해야 하며, 동시에 검사해야 할 파일이 다른 파일에서 호출되더라도 그 내용이 바뀌지는 않습니다. 파일을 확인해야 합니다🎜rrreeerrreee 🎜🎜추천 학습: "🎜PHP 비디오 튜토리얼🎜"🎜

위 내용은 선언(strict_types=1)의 유효한 범위에 대해 이야기해 봅시다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제