- 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前端開發(fā)技術(shù):HTML、CSS、JavaScript(第3版)
- Internet of Things with the Arduino Yún
- SharePoint Development with the SharePoint Framework
- SAP BusinessObjects Dashboards 4.1 Cookbook
- C語(yǔ)言程序設(shè)計(jì)教程
- Learning AngularJS for .NET Developers
- Clean Code in C#
- Visual FoxPro 6.0程序設(shè)計(jì)
- Qlik Sense? Cookbook
- Learning Nessus for Penetration Testing
- 進(jìn)入IT企業(yè)必讀的324個(gè)Java面試題
- Software-Defined Networking with OpenFlow(Second Edition)
- PHP動(dòng)態(tài)網(wǎng)站開發(fā)實(shí)踐教程
- Google Maps JavaScript API Cookbook
- MySQL核心技術(shù)與最佳實(shí)踐