0

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

1
  • As an aside, ereg functions are deprecated, and you should avoid using them. Commented Jul 30, 2012 at 7:13

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 .

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.