This post covers the Type Declarations section of the Functions chapter when studying for the Zend PHP 7 Certification.
You can use type declarations to specify the expected data type of an argument in a function declaration. In PHP 5.5, these were the allowed types introduced.
<?php
class C {}
class D extends C {}
// This doesn't extend C.
class E {}
function f(C $c) {
echo get_class($c)."\n";
}
f(new C);
f(new D);
f(new E);
// Outputs:
C
D
Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given
As of PHP 7.0, support for scalar types such as string, bool, int and float were introduced.
To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL
values if the default value of the parameter is set to NULL
.
<?php
function test(bool $param) {
}
test(true);
By default, type declarations are in coercive
mode. This means that if the type of the argument is not the expected type, PHP will try and correct it.
In strict
mode, if a scalar type is not the expected type, a TypeError
will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float.
To declare strict
mode, use the declare
keyword specifying the strict type.
<?php
declare(strict_types=1);
function addNumbers(int $num1, int $num2) {
return $num1 + $num2;
}
var_dump(addNumbers(1, 2)); // Outputs: int(3)
var_dump(addNumbers(1, 2.5)); // Fatal error
View the other sections:
Note: This article is based on PHP version 7.1.