Recently I had a message board and wanted to give every user a different colour based on their name.
I made the following class:
[php]
<?php
class Colour {
protected $string = '';
private $instance = null;
public function __construct($string) {
$this->string = $string;
}
public function getHEX() {
return '#' . substr(md5(strtolower($this->string)), 0, 6);
}
public function getRGB($opacity = 1) {
$hex = str_replace("#", "", $this->getHEX());
if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b, $opacity);
return 'rgba(' . implode(",", $rgb) . ')';
}
public function setString($string) {
$this->string = $string;
}
public static function getInstance($string = '') {
if (!isset(self::$instance) {
self::$instance = new Colour($string);
} elseif ($string != '') {
self::$instance->setString($string);
}
return self::$instance;
}
}
[/php]
[php]
//It can be used like this:
$colour = new Colour('word');
// Return #289387
echo $colour->getHEX();
// Return RGB rgba(202,111,090,0.4)
echo $colour->getRGB();
//Or use the same instance
// Would both display the same thing.
Colour::getInstance('word')->getRGB();
Colour::getInstance()->getRGB();
[/php]
Hope that helps someone.