PHP 7 – Type Hinting

Tips & Tricks

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.

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:

1
2
3
4
5
6
7
function typeHintingTest(int $value)
{
   return $value;
}

$var = typeHintingTest("5");
var_dump($var);

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.

We can enable this strictness by declaring declare directive like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);

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.

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:

1
2
3
4
5
function returnTypeHinting() : int
{
   return '1';
}
var_dump(returnTypeHinting());

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:

1
2
3
4
5
6
7
8
9
10
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

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

Tags: #PHP

Related Post

Leave a Reply

avatar
  Subscribe  
Notify of