开发者

PHP Constant Conventions

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 purpos开发者_Python百科e.

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?


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.

<?
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'r using PHP 5.3, you can just name the classes Color and Height and put them in a 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;
}


?>


As variant, 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
{

}


Since PHP doesn't have enums your way to do it is perfectly fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜