函数接受整数或数组值

Can I create a PHP function which will accept either integer or array values? Can the logic be determined upon reaching the function, or should it be done prior to calling it? (i.e. I want to avoid using one function for arrays, and another for single integers.)

I could have two arguments one integer, one array, and then call the function with one as null. But is a scenario where I don't know the type at the moment it would be called.

function my_function($integer, array $array)
{
    $integer = '';

    ...

Perhaps, before calling my function, I should convert my integer into a single keyed array so it wouldn't matter.

If you are certain you will only be passing an array or integer type, you could do the following:

function my_function($param)
{
    if (is_array($param)) {
      //treat param as array
    } else {
      //treat param as integer
    }
...
}

PHP does not use strict datatyping. You can always check what type of "object" the argument is:

function my_function($value) {
    if ( is_array($value) ) {
        // it is an array
    } else if ( is_int($value) ) {
        // it is an integer
    } else {
        throw new InvalidArgumentException(__FUNCTION__.' expecting array or integer, got '.gettype($value));
    }
}

PHP has a bunch of type check global functions:

  • is_​array
  • is_​bool
  • is_​callable
  • is_​double
  • is_​float
  • is_​int
  • is_​integer
  • is_​long
  • is_​null
  • is_​numeric
  • is_​object
  • is_​real
  • is_​resource
  • is_​scalar
  • is_​string