Basically, I wish to have 3 printers to print in error state, success state or info state which means nothing but different colors.

    class ColorCode{
        private static $options = [
            "dark_gray"     => "1;30",
            "light_gray"    => "0;37",
            "blue"          => "0;34",
            "green"         => "0;32",
            "cyan"          => "0;36",
            "red"           => "0;31",
            "yellow"        => "1;33"

        public static function get($key){
                return self::$options[$key];
            } else {
                return '';

    class ColorPrint {
        public $color = '';

        function __construct($color) {
            $this->color = ColorCode::get($color);

        public function printc($msg) {
            echo "\033[". $this->color ."m".$msg."\033[0m\n";


    $out = [
        'error'     => new ColorPrint('red'),
        'info'      => new ColorPrint('cyan'),
        'success'   => new ColorPrint('green'),
    $out['error']->printc('Invalid Option');

I like your code, but I just have a couple of small points:

  • Be consistent with your spacing (around { and especially .).
  • I doubt that this will work on Windows, so I would check if the script is run on Windows, if it is, just print without color (or find a way to use color in Windows), and maybe trigger a warning.
  • I would rename printc, either to the shorter print (because it's easier to remember, and you don't really lose any meaning), to print_color (if you want to make it really really explicit that it is in color), or print_console (in case you also later implement something like print_web with CSS).
  • I would not just ignore it if a color is requested that does not exist, but handle it in some way (throw an exception, trigger a warning, etc). Otherwise users might wonder why ligth_gray or orange do not result in any color changes.
  • \$\begingroup\$ isn't print reserved keyword \$\endgroup\$ – aWebDeveloper Jan 19 '15 at 4:45
  • \$\begingroup\$ also how to best throw exception \$\endgroup\$ – aWebDeveloper Jan 19 '15 at 4:46
  • \$\begingroup\$ also what's your view on last 4 lines \$\endgroup\$ – aWebDeveloper Jan 19 '15 at 5:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.