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?
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.
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.
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.
Have a look at Type hinting http://php.net/manual/en/language.oop5.typehinting.php
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());
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