我想尝试
PHP 7的返回类型声明(我在Windows上使用PHP 7RC3用于此目的).
我想从一件非常简单的事情开始:
- function getme() : integer
- {
- return 434;
- }
- echo getme();
但这给了我一个致命的错误:
Fatal error: Uncaught TypeError: Return value of getme() must be an instance of integer,integer returned
然后我也尝试转换返回值,但是
return(整数)434;或return(int)434;给了我同样的错误;
最后我也尝试过:
- function getme() : integer
- {
- $i = 434;
- return (integer) $i;
- }
- echo getme();
结果相同.
我究竟做错了什么?
或者我在这里误解了什么?
感谢您的任何解释和帮助!
UPDATE
这就是为什么我认为我必须使用整数而不是int(特别注意Toby Allen):
从https://wiki.php.net/rfc/return_types:
Examples of Invalid Use
(…)
- // Int is not a valid type declaration
- function answer(): int {
- return 42;
- }
- answer();
No new reserved words are added. The names int,float,string and
bool are recognised and allowed as type declarations,and prohibited
from use as class/interface/trait names (including with use and
class_alias).
来自:https://wiki.php.net/rfc/scalar_type_hints_v5
TL / DR:
- function getme() : int
- {
- return 434;
- }
- echo getme();