Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-函数变量作用域中的函数_Php_Variables_Scope - Fatal编程技术网

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

PHP-函数变量作用域中的函数,php,variables,scope,Php,Variables,Scope,我试图在第二个函数中使用第一个函数的参数作为变量,这就是到目前为止我如何使它工作的,但我怀疑这是一个好方法。请注意,第二个函数(子句where)不能有其他参数 function filtrerDuree($time) { global $theTime; $theTime = $time; function clauseWhere($where = '') { global $theTime; return $where .= " AND

我试图在第二个函数中使用第一个函数的参数作为变量,这就是到目前为止我如何使它工作的,但我怀疑这是一个好方法。请注意,第二个函数(子句where)不能有其他参数

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,例如:strotime('-'.$time.'days'),因为它对第一个函数来说是本地的

在第二个函数中放入全局$time不起作用,即使我在第一个函数中使用了$time=$time


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

我建议不要将函数置于php函数中

我的部分逻辑是关于为什么:

因此,从这篇文章中,理论上可以从外部函数的外部调用内部函数


如果单独调用内部函数,它将不知道变量“$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'))."'";
    });
}

但是内部函数在第一个函数执行之前不存在,因此第二个函数永远不能单独调用。另外,我没有将$time传递给内部函数,因为我无法(解释起来可能很长,但简而言之,这是一个由wordpress操作挂钩调用的回调函数)从另一个函数内部定义函数。在执行外部函数之前,内部函数不存在。