2014-06-18 07:48
浏览 79

为什么不建议在PHP中定义(全局)常量? [关闭]

I heard so many times that use define() to create global constant is a bad solution. But I've never heard why it is so.

And what is the way it should be done instead?

图片转代码服务由CSDN问答提供 功能建议

我听过很多次使用define()来创建全局常量是一个糟糕的解决方案。 但是我从来没有听说过为什么会这样。


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • donglun4682 2014-06-18 07:57

    Probably you've read something about not polluting the global namespace. At least that's the biggest reason why should you try to avoid global constants - and variables and functions for that matter. However there are valid use cases where a global definition makes sense.

    In most cases though the constant belongs to something. That something being a class it's worth defining the constant within the class.

    If you define a constant that has a long prefix (eg. VALIDATOR_EMAIL_PATTERN) that is a sign of a possible class related constant definition (Validator\Email::PATTERN)

    Global definitions have more chance to collide thus making parts of your code harder to re use, since two different library could try to define constants with the same name for their our purpose.

    打赏 评论

相关推荐 更多相似问题