Search code examples
phpstringfunctiontypeshints

Type Hints not working for strings in function in php 7


Type hints doesn't work in case of strings.

function def_arg(int $name, int $address, string $test){
    return $name . $address . $test;
}

echo def_arg(3, 4, 10) ;
// It doesn't throws an error as expected.

On the other hand. if you give string in first argument, it throws an error saying it should be an int.

 function def_arg(int $name, int $address, string $test){
        return $name . $address . $test;
    }

    echo def_arg("any text", 4, "abc") ;

// this code throws an error 
// "Fatal error: Uncaught TypeError: Argument 1 passed to def_arg() must be of the type integer, string given,"

why no error in case of strings ??


Solution

  • This is because by default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

    see here

    If you would use values that could be cast in your second example it would work:

    function def_arg(int $name, int $address, string $test){
        return $name . $address . $test;
    }
    
    echo def_arg("12", "22", 1) ;
    

    This is because those values can be cast from string to int and vise versa.

    It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.