Blank page if I declare(strict_types=1); in PHP 7 at top of the file

倖福魔咒の 提交于 2019-11-29 19:05:16

问题


Recently I was checking out on PHP 7, specifically return type declaration and type hinting. I have compiled PHP 7 from source(master branch from Github) and running it in Ubuntu 14.04 virtual box. I tried to run following code to get a test of new Exceptions. But it Gave a blank page.

<?php

function test(): string {

    return [];
}

echo test();

Then I realize I have to set error to be displayed on screen. So I added old fashioned ini_set('display_errors', 1); like below,

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

function test(): string {

    return [];
}

echo test();

that gave me following TypeError as expected according to this Throwable interface RFC

Fatal error: Uncaught TypeError: Return value of test() must be of the type string, array returned in /usr/share/nginx/html/test.php on line 7 in /usr/share/nginx/html/test.php:7 Stack trace: #0 /usr/share/nginx/html/test.php(10): test() #1 {main} thrown in /usr/share/nginx/html/test.php on line 7

Digging further I added declare(strict_types=1); at the top as below,

<?php declare(strict_types=1);

ini_set('display_errors', 1);

function test(): string {

    return [];
}

echo test();

and bang, error just got disappeared leaving me with blank page. I cant figure out why it is giving me a blank page?


回答1:


After searching around the google and RFC's I came to follwing sentence in RFC,

This RFC further proposes the addition of a new optional per-file directive, declare(strict_types=1);, which makes all function calls and return statements within a file have “strict” type-checking for scalar type declarations, including for extension and built-in PHP functions.

This means there was nothing wrong with directive declare(strict_types=1) but the problem was the way I was calling ini_set() function. It expects second parameter to be of string type.

string ini_set ( string $varname , string $newvalue )

I was passing int instead, and hence the setting needed to display errors itself failed to set and hence I was hit with a blank page by PHP strict mode. I then changed the code a bit and passed the string "1" as below and it worked.

<?php declare(strict_types=1);

ini_set('display_errors', "1");

function test(): string {

    return [];
}

echo test();



回答2:


as the error states your function expect you to return string but instead you return an array! And function complains which is normal. So on your return simply put some string value. That's it!



来源:https://stackoverflow.com/questions/31501219/blank-page-if-i-declarestrict-types-1-in-php-7-at-top-of-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!