我有以下代码:
function lower_than_10($i) {
return ($i < 10);
}
Run Code Online (Sandbox Code Playgroud)
我可以用来过滤这样的数组:
$arr = array(7, 8, 9, 10, 11, 12, 13);
$new_arr = array_filter($arr, 'lower_than_10');
Run Code Online (Sandbox Code Playgroud)
如何向lower_than_10添加参数,以便它还接受要检查的数字?就像,如果我有这个:
function lower_than($i, $num) {
return ($i < $num);
}
Run Code Online (Sandbox Code Playgroud)
如何从array_filter调用它传递10到$ num或任何数字?
基本上我使用这个方便的函数来处理数据库行(关注PDO和/或其他东西)
function fetch($query,$func) {
$query = mysql_query($query);
while($r = mysql_fetch_assoc($query)) {
$func($r);
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个功能,我可以简单地做到:
fetch("SELECT title FROM tbl", function($r){
//> $r['title'] contains the title
});
Run Code Online (Sandbox Code Playgroud)
现在假设我需要$r['title']在var中连接所有内容(这只是一个例子).
我怎么能这样做?我在想这样的东西,但它不是很优雅:
$result = '';
fetch("SELECT title FROM tbl", function($r){
global $result;
$result .= $r['title'];
});
echo $result;
Run Code Online (Sandbox Code Playgroud) function foo () {
global $var;
// rest of code
}
Run Code Online (Sandbox Code Playgroud)
在我的小PHP项目中,我通常采用程序方式.我通常有一个包含系统配置的变量,当我需要在函数中访问此变量时,我会这样做global $var;.
这是不好的做法吗?