Wei Ma
Wei Ma

Reputation: 3165

PHP using array as function

I have created two code snippets at http://codepad.viper-7.com/o5MxgF and http://codepad.viper-7.com/qUpTag

In the second snippet, I was trying to use array as a call back because I found at http://www.php.net/manual/en/language.types.array.php that

Note: Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

So, I thought I could use array as a function so that I don't need the declare

$get_new_key = function ($k) use($fa) {
  return $fa[$k];
};

But as you can see, I was getting a

: array_map() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /code/qUpTag on line 8

error.

Are there anything to make array a callable without creating a companion function to access its values?

Thanks.

Upvotes: 0

Views: 73

Answers (1)

user3477804
user3477804

Reputation:

Having a callable array doesn't mean that it returns the values of the array. Instead, it's an array that points to a method on either a class or object.

For instance, array('MyClass', 'my_method') is a callable for the static method my_method on MyClass and array($object, 'method') is a callable for the instance method method on the object in $object.

You can read more about the callable type in the PHP documentation

Upvotes: 1

Related Questions