PHP permalink

Stackoverflow greetings

I do house cleaning and thought that I would ask for some suggested practices in PHP as I overestimate my classes. In particular, I have some class constants that belong to categories, and I would like to know some good ways to group those that share a common goal.

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 looks like there are plenty of options when it comes to grouping related constants, and I'm sure this is inferior to most. How do you do this?

+4
source share
3 answers

There are many PHP conventions, and they all contradict each other. But I use similar notation, although I like to group constants in a class, so I will have a class Height (or MySquare_Height) that has constants. That way, I can use it as a kind of Enum, as you received in other languages. Especially when you use a backlit editor.

 <? abstract class MySquare_Color { const GREEN = 'Green'; const RED = 'Red'; } abstract class MySquare_Height { const SMALL = 100; const MEDIUM = 300; const BIG = 500; } 

If you are using PHP 5.3, you can simply name the Color and Height classes and put them in the MySquare namespace:

 <?php // Namespace MySquare with subnamespace Width containing the constants. namespace MySquare\Width { const SMALL = 100; const MEDIUM = 300; } namespace { // Refer to it fromout another namespace echo MySquare\Width\SMALL; } ?> 
+4
source

Alternatively, you can create some interfaces where you can define constants. More code, but ... grouped :)

 interface IColorsConstants { const COLOR_GREEN = "green"; const COLOR_RED = "red"; } interface IWidths { const WIDTH_SMALL = 100; const WIDTH_MEDIUM = 500; const WIDTH_BIG = 1000; } interface IHeights { const HEIGHT_SMALL = 100; const HEIGHT_MEDIUM = 300; const HEIGHT_BIG = 500; } class MySquare implements IColorsConstants, IHeights, IWidths { } 
+3
source

Since PHP has no enumerations, your way of doing this is fine.

+1
source

All Articles