【问题标题】:Blank page if I declare(strict_types=1); in PHP 7 at top of the file如果我声明为空白页(strict_types=1);在文件顶部的 PHP 7 中
【发布时间】:2015-10-08 16:10:25
【问题描述】:

最近我正在检查 PHP 7,特别是 return type declarationtype hinting。我已经从源代码编译了 PHP 7(来自Github 的主分支)并在 Ubuntu 14.04 虚拟框中运行它。我尝试运行以下代码来测试新的Exceptions。但它给出了一个空白页。

<?php

function test(): string {

    return [];
}

echo test();

然后我意识到我必须设置要在屏幕上显示的错误。所以我添加了老式的ini_set('display_errors', 1);,如下所示,

<?php
ini_set('display_errors', 1);

function test(): string {

    return [];
}

echo test();

这让我按照Throwable interface RFC 的预期关注了TypeError

致命错误:未捕获的类型错误:test() 的返回值必须是 类型字符串,返回数组/usr/share/nginx/html/test.php 在线 7 在 /usr/share/nginx/html/test.php:7 堆栈跟踪:#0 /usr/share/nginx/html/test.php(10): test() #1 {main} 抛出 /usr/share/nginx/html/test.php 在第 7 行

进一步挖掘,我在顶部添加了declare(strict_types=1);,如下所示,

<?php declare(strict_types=1);

ini_set('display_errors', 1);

function test(): string {

    return [];
}

echo test();

然后砰,错误消失了,给我留下了空白页。我不知道为什么它给了我一个空白页?

【问题讨论】:

    标签: php strict php-7


    【解决方案1】:

    因为错误表明您的函数希望您返回字符串,但您返回的是一个数组!并且功能抱怨这是正常的。因此,在您返回时只需输入一些字符串值。就是这样!

    【讨论】:

      【解决方案2】:

      在搜索了谷歌和 RFC 之后,我找到了 RFC 中的以下句子,

      此 RFC 进一步建议添加一个新的可选 per-file 指令,declare(strict_types=1);,它使所有函数调用 文件中的和 return 语句具有“严格”的类型检查 标量类型声明,包括扩展和内置 PHP 功能。

      这意味着指令declare(strict_types=1) 没有任何问题,但问题在于我调用ini_set() 函数的方式。它期望第二个参数是string 类型。

      string ini_set ( string $varname , string $newvalue )
      

      我改为传递int,因此显示错误所需的设置本身未能设置,因此我被击中 PHP 严格模式下的空白页。然后我稍微更改了代码并传递了字符串"1",如下所示,它起作用了。

      <?php declare(strict_types=1);
      
      ini_set('display_errors', "1");
      
      function test(): string {
      
          return [];
      }
      
      echo test();
      

      【讨论】:

      • 感谢您回来回答这个问题,当我终于开始玩 7 时,我可能会遇到同样的事情
      • 对我很有帮助。你为我节省了很多时间。谢谢。
      猜你喜欢
      • 2016-06-15
      • 1970-01-01
      • 2013-11-30
      • 2013-09-17
      • 1970-01-01
      • 2015-03-21
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多