Home » Php » PHP 7 return type declarations – fatal error

PHP 7 return type declarations – fatal error

Posted by: admin July 12, 2020 Leave a comment

Questions:

I wanted to try out PHP 7’s return type declarations (I am using PHP 7RC3 on windows for this purpose).

wanted to start with something very simple:

function getme() : integer
{
    return 434;
}
echo getme();

but this gives me an fatal error:

Fatal error: Uncaught TypeError: Return value of getme() must be an instance of integer, integer returned

then i also tried to cast the return value, but
return (integer) 434; or return (int) 434; gives me the same error;

finally i also tried:

function getme() : integer
{
    $i = 434;
    return (integer) $i;
}
echo getme();

with the same result.

what am I doing wrong?
or what have I misunderstood here?

thanks for any explanations and help!

UPDATE
this is why I thought I had to use integer instead of int (special note to Toby Allen):

from https://wiki.php.net/rfc/return_types:

Examples of Invalid Use
(…)

// Int is not a valid type declaration

function answer(): int {
    return 42;
}
answer();
How to&Answers:

No new reserved words are added. The names int, float, string and
bool are recognised and allowed as type declarations, and prohibited
from use as class/interface/trait names (including with use and
class_alias).

From: https://wiki.php.net/rfc/scalar_type_hints_v5

TL/DR:

function getme() : int
{
    return 434;
}

echo getme();