Use named constructors when the color is a fixed choice owned by the code, such as the white candidate in a contrast calculation. Parse or inject a value when a theme, configuration file, user, or design token owns the choice.
Distinguish constants from application data
A constructor such as Color::black() communicates a deliberate constant. It should not stand in for a token named text, because that token may change independently of the implementation.
| Source of the decision | Prefer | Example |
|---|---|---|
| Algorithmic constant | Named constructor | Black and white contrast candidates |
| CSS name received as text | Color::parse() |
rebeccapurple from configuration |
| Application token | Dependency or palette entry | text, surface, or brand |
| Numeric color schema | Channel constructor | Known Oklch or sRGB coordinates |
Common sRGB constants are available without parsing:
use PhpColor\Color\Color;
$black = Color::black();
$white = Color::white();
$winner = \PhpColor\Color\Contrast\ContrastSolver::bestOn(
Color::parse('#7c3aed'),
[$black, $white],
);
echo $winner->toHex();
use PhpColor\Color\Color;
$black = Color::black();
$white = Color::white();
$winner = \PhpColor\Color\Contrast\ContrastSolver::bestOn(
Color::parse('#7c3aed'),
[$black, $white],
);
echo $winner->toHex();
The result is #ffffff. In this example, black and white are part of the algorithm's candidate set, so their constructor names explain the decision better than two hexadecimal literals.
Know what the names mean
PHPColor also provides red(), green(), blue(), cyan(), magenta(), yellow(), orange(), purple(), teal(), and gray(). Each returns an SrgbColor with the library's fixed constant value.
These method names are not a semantic color system. Color::red() does not mean an application's danger color, and Color::green() does not guarantee sufficient contrast for success text. Use named palette keys for those roles.
Use Color::parse() for other CSS named colors and for values that cross a text boundary. See Choose text or channel input for that decision, Parse and find named colors for the CSS registry, and Color for the complete constructor list.