14
I was giving a test in PHP 7 and I checked that the same now accepts to define which type of data will 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 should be of the float type
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’t give opinions, because I come from PHP 5 and I don’t know these practices.
What are the advantages of using the definition of return type (return typing)?
How this will help the PHP developer?
I liked the other places of code where it is more difficult to discover.
– Wallace Maxters
Yeah, blowing up somewhere else is one of the things that drives programmers crazy the most.
– Maniero
There was a colleague of mine who searched the entire system for a variable that he never found. He spent a week searching. Then he contacted the programmer and discovered that he had used the variable variable.
$$pog = 'pog'
– Wallace Maxters