在特定函数中无法访问变量?无脂肪框架

Variable not accessible within a particular function? Fat-Free-Framework

会话变量写入成功。我成功地获得了会话变量。我什至可以手动定义它,但它永远不会传递给下面的函数 ($fileBaseName, $formFieldName) 的文件名部分。

非常感谢任何帮助。谢谢!

$uuid = $f3->get('SESSION.uuid'); // get session uuid

$f3->set('UPLOADS', $f3->UPLOAD_IMAGES); // set upload dir

$files = $web->receive(
    function($file,$formFieldName) {

        if($file['size'] > (5 * 1024 * 1024)) // if bigger than 5 MB
            return false; // this file is not valid, return false will skip moving it

        $allowedFile = false; // do not trust mime type until proven trust worthy
        for ($i=0; $i < count($allowedTypes); $i++) {
            if ($file['type'] == $allowedTypes[$i]) {
                $allowedFile = true; // trusted type found!
            }
        }

        // return true if it the file meets requirements
        ($allowedFile ? true : false);
    },

    true, //overwrite

    function($fileBaseName, $formFieldName) {

        $pathparts = pathinfo($fileBaseName);

        if ($pathparts['extension']) {

            // custom file name (uuid) + ext
            return ($uuid . '.' . strtolower($pathparts['extension']));

        } else {
            return $uuid; // custom file name (md5)
        }
    }
);

PHP variable scope

由于变量 $uuid 未定义,它可能超出范围。

您需要将变量传递给您的函数,声明为全局变量,或设置 class 属性(如果这是 class)。如果它在您的会话中设置,您可以直接调用它而无需将它分配给会话加载的任何地方的变量。

您传递给 $web->receive() 的两个函数是 closures。在 PHP 中,闭包看不到在声明它们的范围内声明的变量。要使此类变量可见,可以使用 use 关键字:

$uuid = $f3->get('SESSION.uuid'); // get session uuid

$f3->set('UPLOADS', $f3->UPLOAD_IMAGES); // set upload dir

$files = $web->receive(
    function($file,$formFieldName) {
        //...
    },

    true, //overwrite

    function($fileBaseName, $formFieldName) use ($uuid) {
        //...
    }
);

这应该使 $uuid 在第二个函数中可见。