- 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
推薦閱讀
- 軟件安全技術
- Node.js Design Patterns
- FreeSWITCH 1.8
- The Android Game Developer's Handbook
- 深入淺出DPDK
- 分布式架構原理與實踐
- Application Development with Parse using iOS SDK
- Java Web開發教程:基于Struts2+Hibernate+Spring
- Spring Boot從入門到實戰
- Node.js 6.x Blueprints
- 編程的原則:改善代碼質量的101個方法
- ASP.NET本質論
- Docker on Windows
- Three.js Essentials
- 高性能MVVM框架的設計與實現:San