dongzhiman2162 2012-05-12 14:07
浏览 32

避免始终将变量传递给类

I'm creating a web app in PHP5. So far, I have two "global" variables: $input and $sql. $input is the validated and sanitized input from $_GET, $_POST and $_COOKIE. $sql is an instance of my mysql(i) class.

These two are needed in almost every other class. This could be relatively easily achieved by passing them as parameters to the __construct function of each class. But that seems ... clumsy. Along with more class specific parameters and potential future global vars, it makes for unwieldy function calls.

The easy and, as I understand it, noobie alternative would be using the global keyword. I don't want to do that. I get the downsides of globals, although in my scenario (small app) they wouldn't matter much. But it's also clumsy to explicitely label them global before using them again.

A more elegant way I suppose: I have a webapp class from which I extend all other classes. This webapp class holds common functions I need in more than one other class but that do not warrant for a seperate class. If I store $input and $sql as static variables in this webapp master class, they'd be accessible in all subclasses. But I understand that static variables are as much frowned upon, if not more, than global variables.

Is that true? I guess I'm one of these people who overthink everything, but I like elegant code and this looks elegant to my (amateur) eyes.

  • 写回答

3条回答 默认 最新

  • doumicheng6732 2012-05-12 14:10
    关注

    So far, I have two "global" variables

    Yuck! Globals are bad. :-)

    $input is the validated and sanitized input from $_GET, $_POST and $_COOKIE

    Why do you make that global. Simply sanitize / normalize / whatever when you really are going to use it.

    $sql is an instance of my mysql(i) class.

    Again: no need to make that global. Use dependency injection.

    The easy and, as I understand it, noobie alternative would be using the global keyword. I don't want to do that.

    You are right: you don't want to do that.

    A more elegant way I suppose: I have a webapp class from which I extend all other classes.

    That also doesn't sound really correct. A class has a specific function (/ responsibility).

    But I understand that static variables are as much frowned upon

    Static stuff are just globals with a different name.

    If you do want to make your life easier you could implement a dependency injection container.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型