Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 672
Brook Julias Avatar asked May 02 '12 13:05

Brook Julias


People also ask

Can a parameter be an array?

A parameter array can be used to pass an array of arguments to a procedure. You don't have to know the number of elements in the array when you define the procedure. You use the ParamArray keyword to denote a parameter array.

How do you pass an array as a function argument in PHP?

php function title($title, $name) { return sprintf("%s. %s\r\n", $title, $name); } $function = new ReflectionFunction('title'); $myArray = array('Dr', 'Phil'); echo $function->invokeArgs($myArray); // prints "Dr.

Can we pass function as a parameter in PHP?

There is another type of function known as PHP Parameterized functions, these are the functions with pre defined parameters. You'll pass any number of parameters inside a function. These passed parameters act as variables in your function. They are declared inside the brackets, after the function name.


2 Answers

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

like image 67
Anigel Avatar answered Sep 30 '22 14:09

Anigel


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());
like image 27
Carlos Campderrós Avatar answered Sep 30 '22 16:09

Carlos Campderrós