PHP Tips: Constants as "CSS"

11 January 2012

Disclaimer
I use images to share code, not to be a pain in the arse, but because I don't have the option of bbCode on my site.
I also choose to use an image to share result to avoid having my own CSS interfere with the style.

 

One of my biggest annoyances is the lack of getting CSS classes work with PHP. There might be a way to get it to work that I don't know about. A compromise that I recommend is using constants. It's almost like using CSS within the header tag of every HTML file. It's not dynamic like external CSS files are, but at least they're all grouped at the top of the file for easier access.

One way to declare a constant is to do the following:
const TABLEBORDER = '1';

The name of a constant should always be uppercase, and be descriptive. It makes them stand out more. Like variables a constant should never begin with a number. Only letters or underscores.

To use it, place it inside a HTML tage, like so...
border="', self::TABLEBORDER ,'"

The above code now replaces the need for hardcoded values. My conclusion for self:: is that it's like using the $this-> to refer to objects when calling functions.

 

The full code

code example: constant

 

The result

code example: constant styling table