Search code examples
phpfunctionvariablesparent

Access variable from parent PHP function


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 */
    }
}

Solution

  • 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");