Search code examples
phpfunctionarguments

php: Declare arguments type of a Function


I'm trying to make a function with declared argument types, to quickly check if they are in the right format, but when it returns a string I this error:

Catchable fatal error: Argument 2 passed to myfunction() must be an instance of string, string given, called in path_to_file on line 69 and defined in path_to_file on line 49

Example

function myfunction( array $ARRAY, string $STRING, int $INTEGER ) { 
    return "Args format correct"; 
}
myfunction(array("1",'2','3','4'), "test" , 1234);

Where is the mistake?


Solution

  • According to the PHP5 documentation:

    Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

    Since string and int are not classes, you can't "type-hint" them in your function.

    As of PHP 7.0 declaring argument type as string, int, float, bool is supported.