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.

    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写