Brook Julias
Brook Julias

Reputation: 2105

PHP. Is there a way to require a function parameter to be an array?

Is there a way to require a function parameter is a specific datatype such as an array? For instance something like this:

function example(array $array){}

If so does that work for all datatypes? Is there a good resource that would show me how to do this?

Upvotes: 5

Views: 1677

Answers (2)

Carlos Campderrós
Carlos Campderrós

Reputation: 22972

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

What you want to do is called type-hinting. You can't type hint basic data types, such as int, string, bool. You can type-hint with array or objects and interfaces:

function example_hinted1(array $arr) {

}

function example_hinted2(User $user) {

}

Calling example_hinted1(5) will generate a PHP fatal error (not an exception), but calling it passing an array is totally ok.

If you need to be sure that some argument to a function is from a basic type you can simulate this behavior with code inside your function:

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

So, these snippets would work:

example(1);

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

while these would throw an exception:

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

Upvotes: 3

Anigel
Anigel

Reputation: 3437

Have a look at Type hinting http://php.net/manual/en/language.oop5.typehinting.php

Upvotes: 6

Related Questions