Variables

suggest change

Syntax

Remarks

Type checking

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 is integer and boolean respectively. But for type-hinting for such variables you need to use int and bool. Otherwise PHP won’t give you a syntax error, but it will expect integer and boolean 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:

See also: http://stackoverflow.com/documentation/php/6695/outputting-the-value-of-a-variable

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents