如何使用类方法作为回调函数?
如果我在类函数内使用 array_walk 来调用同一类的另一个函数,
class user
{
public function getUserFields($userIdsArray,$fieldsArray)
{
if((isNonEmptyArray($userIdsArray)) && (isNonEmptyArray($fieldsArray)))
{
array_walk($fieldsArray, 'test_print');
}
}
private function test_print($item, $key)
{
//replace the $item if it matches something
}
}
它会给出以下错误 -
警告:
array_walk()
[function.array-walk]:无法调用test_print()
- 函数不存在于...
那么,如何在使用 array_walk()
时指定 $this->test_print()
代码>?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果要将类方法指定为回调,则需要指定它所属的对象:
来自 手册:
If you want to specify a class method as a callback, you need to specify the object it belongs to:
From the manual:
如果您需要调用静态方法而不实例化该类,您可以这样做:
或者从外部:
If you need to call a static method without instantiating the class you could do so:
Or from outside:
要将一个类方法作为另一个类方法中的回调函数调用,您应该执行以下操作:
To call a class method as a callback function in another class method, you should do :
该类在多维数组中查找特定键并返回其值:
您需要将数组和特定键传递到 get_array() 中。然后调用$result_value:
This is the class which looks for a specific key in a multidimensional array and returns its value:
You need to pass the Array and the specific Key into get_array(). Then call for $result_value:
以下是执行回调函数的四种方法示例。
如果您像我一样,其中之一对您来说将是最直观的。
仔细观察每个 $callable 的定义方式的差异。
重要的是要记住 array_walk() 返回一个布尔值。
这是我使用的单元测试:
Below are four examples of ways to do your callback functions.
If you're like me, one of these will be the most intuitive for you.
Look closely at the difference in how $callable is defined in each one.
It's important to remember that array_walk() returns a boolean.
Here's the unit tests I used: