如何在类内部实现回调方法(PHP)
我需要在另一个方法内的数组上使用类回调方法(回调函数属于该类)。
class Database {
public function escape_string_for_db($string){
return mysql_real_escape_string($string);
}
public function escape_all_array($array){
return array_map($array,"$this->escape_string_for_db");
}
}
这是正确的做法吗? (我的意思是,就传递给 array_map 的第二个参数而言)
I need to use a class callback method on an array inside another method (the callback function belongs to the class).
class Database {
public function escape_string_for_db($string){
return mysql_real_escape_string($string);
}
public function escape_all_array($array){
return array_map($array,"$this->escape_string_for_db");
}
}
Is this the right way to go about that? (I mean, in terms of the second parameter passed to array_map
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您不想array_filter,但是< a href="https://www.php.net/manual/en/function.array-map.php" rel="nofollow noreferrer">array_map
但话又说回来,你也可以这样做
I don't think you want to array_filter, but array_map
but then again, you can just as well do
array_filter
删除不满足谓词的元素。你的意思是array_map
吗?array_filter
deletes elements which does not satisfy the predicate. Do you meanarray_map
?这应该有效。您可以在同一函数中检查您的参数是字符串还是数组。
This should work. You can check in the same function weather your parameter is string or array.
最简单的解决方案是将方法作为回调传递 - 请参阅 http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
或者,编写一个包装函数:
然后:
C.
Simplest solution would be to to pass the method as the callback - see http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
Alternatively, write a wrapper function:
Then:
C.