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?
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
Type declarations can be added to function arguments, return values, and, as of PHP 7.4. 0, class properties. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown. Note: When overriding a parent method, the child's method must match any return type declaration on the parent.
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed. When a function argument is passed by reference, changes to the argument also change the variable that was passed in.
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
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.
This maybe useful for anyone who see this post since the availability of PHP 7
With PHP 7, its now possible to declare types. You can refer the following link for more information.
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
function(string $name, bool $is_admin) { //do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With