我正在查看这个示例array_filter 注释,他将一个参数传递给 array_filter 作为
array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg')
回调如何接受具有多个参数的数组,其中一个是实际的回调函数
我正在查看这个示例array_filter 注释,他将一个参数传递给 array_filter 作为
array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg')
回调如何接受具有多个参数的数组,其中一个是实际的回调函数
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.
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 .
扩展其他答案。在 PHP >= 5.3 中,我们可以使用闭包。
$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.
查看PHP:回调页面。
当为可调用参数指定数组时,您正在指定一个对象和该对象的方法。例如:
$object = new MyClass();
array_filter($input, array($object, 'myClassMethod'));
在您提供的示例中:
array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg');
array_ereg的新实例是对象,而ereg是 array_ereg 类的方法。