0

I am trying to use the argument of the first function as a variable in the second function and this is how I got it to work so far, but I doubt it is the good way. Note that the second function (clauseWhere) can not have other arguments.

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' );
}

I could not use the argument $time directly in the second function like this: strtotime('-' . $time. ' days')), because it is local to the first function anyway.

Putting global $time in the second function did not work, even if I did $time=$time in the first function.

Also, I don't understand why I need to put global on $theTime in the first function...this variable does not exist outside the function, so it's not using any variable outside the function. If I don't put it global, it does not work. I do understand, though, that in the second function I need to put it global.

  • It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed. – Nanhe Kumar Aug 17 '13 at 01:32
  • http://stackoverflow.com/questions/1631535/php-function-inside-function/18284243#18284243 – Nanhe Kumar Aug 17 '13 at 01:32

2 Answers2

0

I'd recommend against putting functions in functions in php.

For part of my logic on why: http://www.php.net/manual/en/language.functions.php#16814

So, from that post, the function inside could theoretically be called from outside of the external function.

If the internal function was called alone, it would not know the variable "$time", and cause lots of problems. I'd recommend not defining the function inside of another, and defining globals outside of the functions, if at all possible. I'm also very confused as far as why you wouldn't just pass the $time variable in to your other function as a parameter.

Lugubrious
  • 380
  • 1
  • 3
  • 16
  • But the inner function does not exist until the first function is executed, so the second function can never be called alone. Also, I am not passing $time to the inner function, because I can't (it would be long to explain, but to make it short, it is a callback function called by a wordpress action hook) –  Aug 17 '13 at 01:10
0

Depending on how add_filter sets up the call to your function you may be able to use a closure and avoid cluttering up global space.

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