Some of the documentation regarding variables and types mentions that PHP does not use static typing. This is correct, but PHP does some type checking when it comes to function/method parameters and return values (especially with PHP 7).
You can enforce parameter and return value type-checking by using type-hinting in PHP 7 as follows:
<?php
/**
* Juggle numbers and return true if juggling was
* a great success.
*/
function numberJuggling(int $a, int $b) : bool
{
$sum = $a + $b;
return $sum % 2 === 0;
}
Note: PHP's
gettype()
for integers and booleans isinteger
andboolean
respectively. But for type-hinting for such variables you need to useint
andbool
. Otherwise PHP won't give you a syntax error, but it will expectinteger
andboolean
classes to be passed.
The above example throws an error in case non-numeric value is given as either the $a
or $b
parameter, and if the function returns something else than true
or false
. The above example is "loose", as in you can give a float value to $a
or $b
. If you wish to enforce strict types, meaning you can only input integers and not floats, add the following to the very beginning of your PHP file:
<?php
declare('strict_types=1');
Before PHP 7 functions and methods allowed type hinting for the following types:
callable
(a callable function or method)array
(any type of array, which can contain other arrays too)See also: Outputting the Value of a Variable