PHP Is there a way for the function parameter to be an array?

Is there a way to require the function parameter to be a specific data type, such as an array? For example, something like this:

function example(array $array){}

If this works for all data types? Is there a good resource that would show me how to do this?

+5
source share
2 answers

Edit: Yes, you can type a hint with arrays, so I edited my answer and changed it accordingly.

What you want to do is called hint type . You can not enter the basic types of tips, such as int, string, bool. You can type a hint using arrayeither objects and interfaces:

function example_hinted1(array $arr) {

}

function example_hinted2(User $user) {

}

example_hinted1(5) PHP ( ), .

, - , :

function example($number) {
  if (!is_int($number) {
    throw new Exception("You must pass an integer to ".__FUNCTION__."()");
  }
  // rest of your function
}

, :

example(1);

$b = 5 + 8;
example($b);

:

example('foo');
example(array(5, 6));
example(new User());
+3

All Articles