PHP 常量约定
问候 StackOverflow
我正在做一些内部清理,并想在重构我的类时询问一些 PHP 中的建议实践。特别是,我有一些属于类别的类常量,我想知道一些对具有共同目的的常量进行分组的好方法。
一个例子:
class MySquare {
// Colors
const COLOR_GREEN = "green";
const COLOR_RED = "red";
// Widths
const WIDTH_SMALL = 100;
const WIDTH_MEDIUM = 500;
const WIDTH_BIG = 1000;
// Heights
const HEIGHT_SMALL = 100;
const HEIGHT_MEDIUM = 300;
const HEIGHT_BIG = 500;
}
显然这是可行的,但是在对相关常量进行分组时似乎有很多选择,我敢打赌这比大多数选项都要差。你会怎么做?
Greetings StackOverflow
I'm doing some house cleaning and thought I would ask for some suggested practices in PHP as I re-factor my classes. In particular, I have some class constants which fall into categories and I would like to know some good ways to group the ones which share a common purpose.
An Example:
class MySquare {
// Colors
const COLOR_GREEN = "green";
const COLOR_RED = "red";
// Widths
const WIDTH_SMALL = 100;
const WIDTH_MEDIUM = 500;
const WIDTH_BIG = 1000;
// Heights
const HEIGHT_SMALL = 100;
const HEIGHT_MEDIUM = 300;
const HEIGHT_BIG = 500;
}
Obviously this works, but it seems like there are probably plenty of options when it comes to grouping related constants, and I bet this is inferior to most. How would you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 约定有很多,而且全都互相矛盾。但我确实使用了类似的符号,尽管我喜欢将每个类的常量分组,所以我会有一个类
具有常量的高度(或 MySquare_Height)。这样,我可以将它用作一种枚举,就像在其他语言中一样。特别是当您使用带有突出显示功能的编辑器时。
如果您使用 PHP 5.3,则只需将类命名为 Color 和 Height 并将它们放入 MySquare 命名空间中:
There are many PHP Conventions, and all of them contradict. But I do use a similar notation, although I like to group the constants per class, so I would have a class
Height (or MySquare_Height) which has the constants. This way, I can use it as a kind of Enum like you got in other languages. Especially when you use an editor with highlighting.
If you'r using PHP 5.3, you can just name the classes Color and Height and put them in a MySquare namespace:
作为变体,您可以创建一些接口,在其中可以定义常量。更多代码,但是...分组:)
As variant, you can create some interfaces, where you can define constants. More code, but... grouped :)
由于 PHP 没有枚举,因此您的做法完全没问题。
Since PHP doesn't have enums your way to do it is perfectly fine.