如何封装一个文件包含?
如果我有一个包含带有常量的文件的类,如下所示:
define("FOO", "bar");
有没有办法使该类包含带有封装的文件,因此如果我在已经定义了 FOO
常量的地方使用该类不会坏吗?
If I have a class that includes a file with a constant like so:
define("FOO", "bar");
Is there a way to make the class include the file with encapsulation so if I use the class somewhere that already has a FOO
constant defined it won't break?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个静态类并使用常量将是封装特定常量的最佳方法:
然后像这样使用:
关于预检查,您可以执行
用法:
如果您想到这样的情况,
则常量在类范围内,因此它们不会互相影响!
Create a static class and use constants would be the best way to encapsulate specific constants:
And then use like so:
in regards to the precheck you can do
Usage:
If your thinking of a situation like so
the constants are within the class scope so they would have no affect on one another !
您可以使用
define
检查常量是否已定义:You can check if constant already defined using
defined
:您可以使用类常量,
但是,您必须先包含该类,然后才能在
Foo::FOO
中使用该常量。常规常量的另一种替代方法是使用供应商前缀为它们添加前缀,以减少冲突的可能性,例如或使用新引入的命名空间(PHP 5.3)
但在所有情况下,我想知道为什么你需要它。如果你想加载类,只需添加 自动加载器。
You can use a class contant
However, you will have to include the class before you can use the constant with
Foo::FOO
. An alternative with regular constants is to use to prefix them with a vendor prefix to make clashes less likely, e.g.or use the newly introduced namespaces (PHP 5.3)
But in all cases, I wonder why you would need that. If you want to load classes, simply add in an autoloader.