从父PHP函数访问变量

时间:2014-02-14 17:05:11

标签: php function variables parent

是否可以从父函数中获取变量而不在调用函数时在括号中声明该函数(在此实例中不可能)。

function list_posts($filter_by_date){

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

4 个答案:

答案 0 :(得分:3)

您可以使用闭包:

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

答案 1 :(得分:1)

是的,单独声明它们并使用参数:

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

答案 2 :(得分:1)

是的,如果您使用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();
}

答案 3 :(得分:0)

您可以使用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;
}