7

我想尝试 PHP 7 的返回类型声明(为此我在 windows 上使用 PHP 7RC3)。

想从非常简单的事情开始:

function getme() : integer
{
    return 434;
}
echo getme();

但这给了我一个致命的错误:

致命错误:未捕获的TypeError:getme()的返回值必须是整数的实例,返回整数

然后我也尝试转换返回值,但是 return (integer) 434;还是return (int) 434;给了我同样的错误;

最后我也试过:

function getme() : integer
{
    $i = 434;
    return (integer) $i;
}
echo getme();

结果相同。

我究竟做错了什么?
或者我在这里误解了什么?

感谢您的任何解释和帮助!

更新
这就是为什么我认为我必须使用integer而不是int(托比艾伦特别注意):

来自https://wiki.php.net/rfc/return_types

无效使用示例 (...)

// Int is not a valid type declaration

function answer(): int {
    return 42;
}
answer();
4

1 回答 1

15

不添加新的保留字。名称 int、float、string 和 bool 被识别并允许作为类型声明,并且禁止用作类/接口/特征名称(包括 use 和 class_alias)。

来自:https ://wiki.php.net/rfc/scalar_type_hints_v5

TL/DR:

function getme() : int
{
    return 434;
}

echo getme();
于 2015-09-19T08:11:52.913 回答