LMLPHP后院

PHP7 返回值类型与声明不符报错技术

maybe yes 发表于 2017-07-25 10:52

PHP7函数方法支持声明返回值类型,出于好奇,试了下如果在运行时返回值类型与声明不符会怎么样?

<?php

function test() : array{
    return 'lmlphp';
}

test();

如下致命错误

PHP Fatal error:  Uncaught TypeError: Return value of test() must be of the type array, string returned in /home/may/work/code/repo/lmlphp.com/temp1.php:4
Stack trace:
#0 /home/may/work/code/repo/lmlphp.com/temp1.php(7): test()
#1 {main}
  thrown in /home/may/work/code/repo/lmlphp.com/temp1.php on line 4

觉得这玩意儿对于解释性执行意义不大,Java 的强类型导致人家的 IDE 能够做的相当的强大和智能,这个是弱类型语言无法做到的,这声明了类型在运行时才会抱错,不是自己给自己找事情吗?难道只是为了阅读上的方便?

2025-06-17 12:27:28 1750134448 0.010170