- Building RESTful Web Services with PHP 7
- Haafiz Waheed ud din Ahmad
- 132字
- 2021-07-03 00:02:22
Return type declaration
Just like parameter type, there is also a return type; it is also optional but it is a safe practice to specify the return type.
This is how we can declare a return type:
<?php
function add($num1, $num2):int{
return ($num1+$num2);
}
echo add(2,4); //6
echo add(2.5,4); //6
As you can see in the case of 2.5 and 4, it should be 6.5, but as we have specified int as a return type, it is performing implicit type conversion. To avoid this and to obtain an error instead of an implicit conversion, we can simply enable a strict type, as follows:
<?php
declare(strict_types=1);
function add($num1, $num2):int{
return ($num1+$num2);
}
echo add(2,4); //6
echo add(2.5,4); //Fatal error: Uncaught TypeError: Return value of add() must be of the type integer, float returned
推薦閱讀
- Python數據分析入門與實戰
- Java高并發核心編程(卷2):多線程、鎖、JMM、JUC、高并發設計模式
- ASP.NET Core 5.0開發入門與實戰
- Mastering Selenium WebDriver
- C語言程序設計實訓教程
- Windows Presentation Foundation Development Cookbook
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- 零基礎學Java程序設計
- JavaScript+Vue+React全程實例
- Mastering ServiceNow(Second Edition)
- Android Native Development Kit Cookbook
- Hands-On Reinforcement Learning with Python
- 數據結構案例教程(C/C++版)
- Spring快速入門
- HTML 5與CSS 3權威指南(第3版·上冊)