0

Is it possible to obtain a variable from a parent function without declaring that function in parenthesis when calling the function (not possible in this instance).

function list_posts($filter_by_date){

    /* Dome things to do first 8*/
    function filter(){
        /* Do something that involves the variable $filter_by_date */
    }
}

4 Answers 4

3

You can use closures:

function list_posts($filter_by_date){

    /* Dome things to do first 8*/
    $filter = function() use($filter_by_date) {
        echo $filter_by_date; // outputs "test"

        /* Do something that involves the variable $filter_by_date */
    };

    $filter();
}

list_posts("test");
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, declare them separately and use arguments:

function filter($arg){
    echo 'filter() got: ', $arg, PHP_EOL;
}

function list_posts($filter_by_date){

    echo 'list_posts() got: ', $filter_by_date, PHP_EOL;

    filter($filter_by_date);
}

list_posts(date('d.m.Y'));

Comments

1

Yes, this is possible if you use a anonymous function:

function list_posts($filter_by_date) {

    // Dome things to do first 8*/
    $filter = function () use($filter_by_date) {
        // Do something that involves the variable $filter_by_date
    };

    // Call the filter function
    $filter();
}

Comments

0

You can use global.

function list_posts($filter_by_date){
    global $filter_by_date;

     // do something with variable
}

function filter(){
    global $filter_by_date;

    echo $filter_by_date;
}

4 Comments

Well, in global scope might be a race conditions. So, in perspective, it is not a reliable approach.
But it's still another option.
Yes, that's why I'm not downvoted. It only might be used bad.
This one doesn't do alas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.