Hello Friends,
Today, We will discuss a new feature Return type declaration which is introduced in Php 7. Return type declaration refers the type of the value that a function should return.
Following is the declaration type supported by the Php 7.
int
float
bool
string
interfaces
array
callable
We can see the following example of a simple function without return type:
<?php
function test()
{
return[];
}
var_dump( test() );
Above example return result: arry(0) {}
We didn't define declaration type in above example.
But in Php 7 we can declare the functions with it's return type. It is not necessary to declare in Php 7, but if we want to improve our coding standards then we can use php 7 this feature in our programming.
We need to define return type between function after closing parenthesis ) and open curly braces { as below example.
Following example of a simple function for with return type declaration:
<?php
declare( strict_types = 1 );
function test() : array //return type declaration
{
return 4;
}
var_dump( test() );
In above example we can see that our function test return integer type value and we declare the return type array. It this example the code will generate a fatal error for return value.
find the screen shot for the fatal error.
Following example will work fine with return type declaration:
<?php
declare( strict_types = 1 );
function test() : array //return type declaration
{
return [];
}
var_dump( test() );
above example return result without any error.
Thanks,
Vipul Srivastava
0 Comment(s)