Home > database >  acess variable in sub function
acess variable in sub function

Time:10-11

I made this function and observed there was an issue during it execution. I'm not able to get the result of $names_from_source inside the sub function. There is no error, it detects the variable but it value is always NULL.

/*
source: array of MyObject
copy: array of MyObject
return: return duplicated objects based on name
*/
function get_all_duplicated($source, $copy) {
    $names_from_source = array_map(fn($obj): string => $obj->name, $source);
    var_dump($names_from_source); // return list of names
    return array_filter($copy, function($obj) {
        global $names_from_source;
        var_dump($names_from_source); // return NULL
        return in_array($obj->name, $names_from_source);
    });
}

Why? Thanks

CodePudding user response:

global couldn't be used because $names_from_source isn't a global variable. It is a local variable from parent function.

to call it in sub function I have to use the term use

/*
source: array of MyObject
copy: array of MyObject
return: return duplicated objects based on name
*/
function get_all_duplicated($source, $copy) {
    $names_from_source = array_map(fn($obj): string => $obj->name, $source);
    var_dump($names_from_source); // return list of names
    return array_filter($copy, function($obj) use($names_from_source) {
        return in_array($obj->name, $names_from_source);
    });
}
  • Related