Web Development

PHP 7 – Type Hinting

Few years back, I have written article on Type Hinting with PHP. In that, I have clearly mentioned that type hinting is not possible with scalar data types like integer, string, float and booleans.

PHP7 Type Hinting

But with PHP 7, it is not possible to set type hinting for Scalar Data Types. This is introduced at two levels, which are scalar type hinting for function/method arguments and scalar type hinting for function/method return type.

[gads]

Type Hinting for Arguments

Same as earlier we can define type hinting for scalar data types as well, let’s see that in code block below:

[cc lang=”php”]
function typeHintingTest(int $value)
{
return $value;
}

$var = typeHintingTest(“5″);
var_dump($var);
[/cc]

In the above code you can see that we have type hinting is defined as an integer but an argument is passed as string (Note the quotes). It’s because type hinting in PHP 7 is non-restrictive, which means PHP will correct parameter on its own. That is the reason it is not generating any kind of error and/or warnings.

[gads]

We can enable this strictness by declaring [code]declare[/code] directive like below:

[cc lang=”php”]
declare(strict_types = 1);

function typeHintingTest(int $value)
{
return $value;
}

// Error: Fatal error: Uncaught TypeError: Argument 1 passed to typeHintingTest() must be of the type integer, string given.
$var = typeHintingTest(“5”);
var_dump($var);

// This will execute successfully.
$var = typeHintingTest(5);
var_dump($var);
[/cc]

Type Hintinng for Return Type

With PHP7, same as above section we can define type hinting for function return type as well. Type hinting for function return type is a new introduction for PHP world.

[gads]

Same as argument type hinting, this type hinting is also non-restrictive and we can enable the strictness as mentioned in the above section. Let’s look into some code now:

[cc lang=”php”]
function returnTypeHinting() : int
{
return ‘1’;
}
var_dump(returnTypeHinting());
[/cc]

The above code will not generate any error/warning and continue execution by converting the return value to the defined return type. For the script mode same code can be written as below:

[cc lang=”php”]

declare(strict_types = 1);

function returnTypeHinting() : int
{
return ‘1’;
}
var_dump(returnTypeHinting());

// Error:
// Fatal error: Uncaught TypeError: Return value of returnTypeHinting() must be of the type integer, string returned

[/cc]

Hope you find this piece of PHP 7 interesting and useful but for now let’s wait and watch for PHP 7 stuff.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *