PHP-函数变量作用域中的函数


PHP - Function in a function variable scope

我正试图将第一个函数的参数用作第二个函数中的变量,这就是我迄今为止如何使其工作的方法,但我怀疑这是否是一种好方法。请注意,第二个函数(clauseWhere)不能有其他参数。

function filtrerDuree($time) {
    global $theTime;
    $theTime = $time;
    function clauseWhere($where = '') {
        global $theTime;
        return $where .= " AND post_date > '" . date('Y-m-d', strtotime('-' . $theTime. ' days')) . "'";
    }
    add_filter( 'posts_where', 'clauseWhere' );
}

我不能在第二个函数中直接使用参数$time,如下所示:strtotime('-'.$time.'days'),因为它无论如何都是第一个函数的本地参数。

在第二个函数中放入全局$time是无效的,即使我在第一个函数中使用了$time=$time。

此外,我不明白为什么我需要在第一个函数中对$Time设置global。。。这个变量不存在于函数之外,所以它没有使用函数之外的任何变量。如果我不把它放在全球范围内,它就不起作用。不过,我确实理解,在第二个函数中,我需要将其全局化。

我建议不要将函数放在php中的函数中。

关于原因的部分逻辑:http://www.php.net/manual/en/language.functions.php#16814

因此,从那个帖子中,内部函数理论上可以从外部函数的外部调用。

如果单独调用内部函数,它将不知道变量"$time",并导致许多问题。如果可能的话,我建议不要在另一个函数内部定义函数,而在函数外部定义全局。我也很困惑,为什么不把$time变量作为参数传递给另一个函数。

根据add_filter如何设置对函数的调用,您可能可以使用闭包来避免混淆全局空间。

function filtrerDuree($time) {
    add_filter( 'posts_where',  function($where) use ($time){
        return $where .= " AND post_date > '" . date('Y-m-d', strtotime('-'.$time.' days'))."'";
    });
}