Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
oscurodrago Avatar asked Jan 22 '12 16:01

oscurodrago


People also ask

How can you get the type of arguments passed to a function?

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.

What is type declaration in PHP?

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.

What is function argument PHP?

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.

Can we use variable number of arguments for a function in PHP?

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.


2 Answers

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.

like image 180
ldiqual Avatar answered Sep 25 '22 05:09

ldiqual


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 } 
like image 36
Amal Ajith Avatar answered Sep 25 '22 05:09

Amal Ajith