I was giving a test in PHP 7 and checked that it now accepts to define which type of data is going to be returned.
Here are some tests:
Defining the instance to be returned
function test_object(): stdClass {
return new ArrayObject;
}
Fatal error: Uncaught TypeError: Return value of test_object () must be an instance of stdClass, instance of ArrayObject returned
Defining that the return must be of type float
function test_type(): float
{
return 1; // Nesse caso, retorna float(1)
}
function test_type(): int
{
return 1;// Nesse caso retorna int(1)
}
function test_type(): string
{
return 1 + 1; // Nesse caso retorna string(2)
}
function test_type(): string {
return array(1, 2, 3); // Fatal error
}
Fatal error: Uncaught TypeError: Return value of test_type () must be of the type string, array returned
Some people may even have positive views on this, but I can not give opinions, as I come from PHP 5 and I do not know these practices.
What are the advantages of using the return type definition (return type)?
How will this help the PHP developer?