Aks
Aks

Reputation: 5236

Passing array instead of callback in array_filter

I'm looking at this example array_filter comment and he passes an argument to array_filter as

array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg')

How is it that the callback accepts an array with multiple arguments one of them being the actual callback function

Upvotes: 0

Views: 1106

Answers (4)

E.J. Sexton
E.J. Sexton

Reputation: 21

Have a look at the PHP: Callbacks page.

When an array is specified for a callable parameter, you are specifying an object and a method of that object. For example:

$object = new MyClass();
array_filter($input, array($object, 'myClassMethod'));

In the example you provided:

array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg');

The new instance of array_ereg is the object and ereg is the method of the array_ereg class.

Upvotes: 0

pamil
pamil

Reputation: 980

To extend other answers. In PHP >= 5.3, we can use closures.

$numbers = range(1,10);
$newNumbers = array_filter($numbers, function($value) {
    return ($value & 1) === false;
});
// $newNumbers now contains only even integers. 2, 4, 6, 8, 10.

Upvotes: 0

lll
lll

Reputation: 12889

In PHP it is possible to represent a callable using an array in the following format.

array($object, 'methodName')

The documentation itself states:

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

It is quite common to see this used with the $this variable inside objects.

In your example, the first element of the array is created with new, and is the instantiated object required, and ereg is the method.

Upvotes: 1

complex857
complex857

Reputation: 20753

The array_filter functions expects a callable for it's second parameter. PHP understands an array($instance, 'methodname') as callable for instance methods, and array('classname', 'staticmethodname') for static methods (or simple 'classname::staticmethod' since version 5.2.3 .

Upvotes: 1

Related Questions