gpt4 book ai didi

php - (php) 如何在 array_filter 中传递类方法作为回调?

转载 作者:行者123 更新时间:2023-12-02 17:31:47 24 4
gpt4 key购买 nike

调用array_filter时使用 php 函数你应该这样做

function myFunc($e) {
return something($e);
}
array_filter($myArray,"myFunc");

但是我如何传递类方法呢? (静态或非静态)例如

class A {
public function foo() {
//code
$a = array_filter($array,"self::myFilter");
//or if myFilter is an instance method
$a = array_filter($array,"this->myFilter");
}
public (static)? function myFilter($e) {return something($e);}
}

我需要,因为我将在类中的其他地方重用我的过滤函数,我尝试在静态变量中使用匿名函数,但出现错误

最佳答案

这应该适用于实例方法版本:

class A {
public function foo() {
$a = array_filter($array, array($this, "myFilter"));
}
public function myFilter($e) {return something($e);}
}

参见http://php.net/manual/en/language.types.callable.php

关于php - (php) 如何在 array_filter 中传递类方法作为回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com