- 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
推薦閱讀
- Web交互界面設計與制作(微課版)
- Python進階編程:編寫更高效、優雅的Python代碼
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- Interactive Applications Using Matplotlib
- Learning Laravel's Eloquent
- 從零開始學Linux編程
- NGINX Cookbook
- Java零基礎實戰
- Hands-On Nuxt.js Web Development
- 從零開始:UI圖標設計與制作(第3版)
- Visual Studio Code 權威指南
- 數據分析與挖掘算法:Python實戰
- 現代CPU性能分析與優化
- Tableau Dashboard Cookbook
- Apache Solr for Indexing Data