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

时间:2017-01-18 20:20:51

标签: php 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)
        }
    }
);

2 个答案:

答案 0 :(得分:2)

您传递给$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在第二个函数中可见。

答案 1 :(得分:0)

PHP variable scope

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

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