Strong typing in PHP. Code example open

Strong typing in PHP. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7

Strong typing was introduced in PHP 7, thanks to which it became possible to specify the types of arguments to functions (methods) and the return type.

By default, PHP 7, when operating in loosely typed mode, will try to convert values of another type to the expected scalar type if possible.

function getAge (string $age ) { 
    var_dump ($age); 
} 

$age = 33; 
getAge($age); 
// string (2) "33" 

Without strong typing, PHP converted the integer 33 to the string “33” as expected.

PHP 7 introduced the declare(strict_types=1); directive, which enables strict mode. In strict mode, only a variable of the exact, given type will be accepted, or a TypeError will be thrown. The only exception to this rule is that a function that expects a float can return an integer.

Now our past example will output an error and will not work:

declare(strict_types = 1);

function getAge(string $age) {
 var_dump($age);
}

$age = 33;
getAge($age);

By running the code, we take:

//Fatal error: Uncaught TypeError: Argument 1 passed to getAge() must be of the type string, integer given..

! The only exception to the strong typing rule is that a function that expects a float can return an integer:

Note that enabling strong typing will also affect return type declarations – with strong typing, the return value must be of the same type as the specified type, or a TypeError will also be thrown.
declare(strict_types = 1);

function getFloat(float $f) : int 
{
    return (int) $f;
}

$int = getFloat(100);
0

More

Leave a Reply

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

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation