【问题标题】:PHP Anonymous Function, Use Keyword & Variable Scope IssuePHP匿名函数,使用关键字和变量范围问题
【发布时间】:2015-01-08 06:21:46
【问题描述】:

作为参考,我使用的是 SLIM 框架

我的问题是您在下面的代码中看到注释掉的 print_r 命令。出于某种原因,该变量在 !in_array 函数之前显示了正确的值。我不确定发生了什么,但是当您将变量 $allowedUserTypes 传递给该函数时,它似乎正在使用(我从某处猜测变量的旧版本)不正确的值。不知道这是怎么可能的,因为它在该功能之前就可以工作???。我猜测存在某种范围问题,或者我误解了匿名函数中“USE”关键字的使用。

$validate_user = function ($allowedUserTypes, $templateFolder = 'api'){
    return function() use ($allowedUserTypes, $templateFolder){
        global $app, $settings, $user, $device;

        set_template_directory($templateFolder);

        $errors = array();

        $validated = true;//assumed valid until proven false.

        //check session variables only if not token api call
        if($app->request()->params('token') == ''){

            //Check for expiration date hack
            if($_SESSION['remember']==false){
                $now = new DateTime();
                $now->modify("-30 minutes");
            }else{
                $now = new DateTime();
                $now->modify("-14 days");
            }

            //If the cookie still exists then it might have a time value in it.  See if it's set.
            if(isset($_SESSION['time'])){
                //If time now (minus minute) is greater than the session time then hack attempted.
                if($now > $_SESSION['time']){ 
                    $errors["errors"]["generic"][] = "Permission denied.  Cookie expired.";
                    $validated = false;
                    unset($_SESSION['time']);
                    unset($_SESSION['remember']);
                    unset($_SESSION['userid']);
                    unset($user);
                }
            }
        }

        if(isset($user)){
            $usertype = Usertype::find_by_id($user->usertype_id);//get all usertypes

            //print_r($allowedUserTypes); --> shows Admin, Manager, Franchise Admin, Franchise Manager
            if(!in_array($usertype->name,$allowedUserTypes)){
                //print_r($allowedUserTypes); --> shows only Admin, Manager ??

                $errors["errors"]["generic"][] = "Permission denied for user type :".$usertype->name;
                $validated = false;
            }
        }else{
            $errors["errors"]["generic"][] = "Permission denied.  User not logged in.  Please log in and try again.";
            $validated = false;
        }

        if($validated==false){
            $errors["command"] = "Error";
            $errors['message'] = "User could not be validated.";

            if($templateFolder=='templates'){
                $app->render('shared/header.php',       array('settings' => $settings));
                $app->render($device.'/header.php',     array('settings' => $settings, 'pagetitle'  => 'Pool Service USA | Error Page', 'user' => $user));
                $app->render($device.'/error.php',      array('settings' => $settings, 'errors' => $errors,'device' => $device));
                $app->render($device.'/footer.php',     array('settings' => $settings));
                $app->render('shared/footer.php',       array('settings' => $settings));
            }else{ //API Based Errors
                $app->render('shared/error.php', array(
                    'settings'  => $settings,
                    'errors'    => $errors,
                    'device'    => $device
                ));
            }

            $app->stop();//stop rendering to this point.
        }
    };
};

我将在调用该函数之前和之后显示用于调用此函数的 2 行代码。

$app->map('/api/remove-user'                        ,'get_user',$validate_user(array('Admin','Manager','Franchise Admin','Franchise Manager')),$remove_record_for_class('User'))                                ->via('GET', 'POST');
$app->map('/api/view-user'                          ,'get_user',$validate_user(array('Admin','Manager','Franchise Admin','Franchise Manager')),$view_results_for_class('User'))                                 ->via('GET', 'POST');

欢迎提出任何建议!

【问题讨论】:

  • 有什么理由使用匿名函数作为另一个函数中的唯一代码。我知道如果您删除 return function() use ($allowedUserTypes, $templateFolder){ 并且它对应的结尾是 },它应该会起作用。
  • 我不得不这样做,因为 slim 需要在其 $app-map() 函数中返回一个函数,但我找到了解决方案,我通过两次调用 $app->map 犯了一个错误,我认为发生的事情是 git 合并到它的副本中并将我搞砸了。

标签: php scope anonymous-function slim


【解决方案1】:

原来我偶然运行了两次 $app->map('') 命令,在一种情况下只发送了导致错误的“Admin”和“Manager”。所以我犯了一个愚蠢的错误:(。只是去表演以提防这些东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    相关资源
    最近更新 更多