如何在子函数中使用函数变量

时间:2014-07-12 15:55:48

标签: php

所以我有以下功能:(这应该是最新版本)

function getLatestVersion($type){

    $searchString['Smarty']     = "php/Smarty-*";
    $searchString['jQuery']     = "js/jQuery-*";
    $searchString['jQueryUI']   = "js/jQueryUI-*";
    $searchString['Bootstrap']  = "js/bootstrap-*";

    $versions = glob($searchString[$type]);

    $latests = array_reduce($versions, function ($latest, $folder) {

        if (!$latest) {
            return $folder;
        }

        $latestNum = preg_replace('!^' . substr($searchString[$type],0,-1) . '!', '', $latest);
        $folderNum = preg_replace('!^' . substr($searchString[$type],0,-1) . '!', '', $folder);

        return version_compare($latestNum, $folderNum, '>') ? $latest : $folder;

    });
    return $latests;
}

但这会导致错误

Notice: Undefined variable: searchString in....
Notice: Undefined variable: type in....

问题:为什么我不能在该子功能中使用变量?

我的尝试:

....
$latests = array_reduce($versions, function ($latest, $folder) {
    echo $latest, $folder;
    if (!$latest) {
        return $folder;
    }
    global $searchString, $type; //but the variables are empty
    $latestNum = preg_replace('!^' . substr($searchString[$type],0,-1) . '!', '', $latest);
    $folderNum = preg_replace('!^' . substr($searchString[$type],0,-1) . '!', '', $folder);

    return version_compare($latestNum, $folderNum, '>') ? $latest : $folder;

});
....

1 个答案:

答案 0 :(得分:1)

这很简单:

function ($latest, $folder) use ($searchString, $type) {

要使用父作用域中的变量,请使用use;)