doufan6886 2011-10-06 14:50
浏览 15
已采纳

PHP脚本结构和范围,以避免不必要的函数参数

Lets say you have an program like this:

$info = array(
    'username'=>'jeff',
    'password'=>'kay'
);

function authenticate($user, $pass) {
    if($user == $info['username'] && $pass == $info['password']) {
        return true;
    }
    return false;
}

This code won't work because the $info array isn't in authenticate()'s scope. You would have to pass $info as a parameter of authenticate() like so:

function authenticate($info, $user, $pass) { // ... }

This feels wrong to me.

I could certainly add global $info; inside of authenticate but that feels even more wrong. What is best practice for structuring a PHP program to avoid scope issues like this? You don't see functions requiring you to pass in the 'global' object in modern code it seems like. How do I avoid unnecessary function arguments?

  • 写回答

6条回答 默认 最新

  • doutu1939 2011-10-06 20:58
    关注

    Most people do not notice, but this is actually a very good question.

    Many other languages (especially functional ones) have lexical scope. With PHP 5.3 lambdas you get that capability, but only within lambdas. Let me show you what I mean:

    $info = array(
        'username'=>'jeff',
        'password'=>'kay'
    );
    
    $authenticate = function ($user, $pass) use ($info) {
        if ($user == $info['username'] && $pass == $info['password']) {
            return true;
        }
        return false;
    }
    
    if ($authenticate($_POST['username'], $_POST['password'])) {
        // use authenticated
    }
    

    With the use you can import variables from the outer scope, but it only works for anonymous functions. It really depends on what kind of style and framework you're coding in/with.

    If you don't want to define these inline (since you must assign them to variables, which is not so nice), I'd suggest you go with your instincts, so pass $info into authenticate or make $info an instance variable of the class that authenticate belongs to.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?