相关疑难解决方法(0)

带有参数的PHP array_filter

我有以下代码:

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或任何数字?

php arrays

96
推荐指数
7
解决办法
7万
查看次数

使用匿名函数作为参数访问外部变量

基本上我使用这个方便的函数来处理数据库行(关注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)

php closures scope

89
推荐指数
1
解决办法
4万
查看次数

PHP中的全局变量是否被视为不良做法?如果是这样,为什么?

function foo () {
    global $var;
    // rest of code
}
Run Code Online (Sandbox Code Playgroud)

在我的小PHP项目中,我通常采用程序方式.我通常有一个包含系统配置的变量,当我需要在函数中访问此变量时,我会这样做global $var;.

这是不好的做法吗?

php global global-variables

84
推荐指数
5
解决办法
3万
查看次数

标签 统计

php ×3

arrays ×1

closures ×1

global ×1

global-variables ×1

scope ×1