webservco / constant-value-class
A PHP library. Type-checked constants for PHP 7: a class whose only instances are its own constant values, so it can stand in for an enum.
Requires
- php: ^7.4||^8.1
Requires (Dev)
- pds/skeleton: ^1
- phan/phan: ^5
- php-parallel-lint/php-console-highlighter: ^1
- php-parallel-lint/php-parallel-lint: ^1
- phpcompatibility/php-compatibility: @dev
- phpmd/phpmd: ^2
- phpstan/phpstan: ^1
- phpstan/phpstan-strict-rules: ^1
- phpunit/phpunit: ^9
- slevomat/coding-standard: ^8
- squizlabs/php_codesniffer: ^3
- vimeo/psalm: ^4
Suggests
- phpdocumentor/phpdocumentor: phpDocumentor v3 (global installation)
Provides
None
Conflicts
None
Replaces
None
README
A PHP library.
Type-checked constants for PHP 7: a class whose only instances are its own constant values, so it can stand in for an enum.
Note: PHP 8.1 and later have native enumerations. Prefer those in new code.
- Requires: PHP 7.4 or 8.1+
- Based on: "Expressive, type-checked constants for PHP"
Installation
composer require webservco/constant-value-class
Usage
Implement the interface, use the trait, and add a static method for each constant.
use WebServCo\ConstantValueClass\ConstantValueClassInterface; use WebServCo\ConstantValueClass\ConstantValueClassTrait; final class ShipmentType implements ConstantValueClassInterface { use ConstantValueClassTrait; private const EXPORT = 1; private const IMPORT = 5; public static function export(): self { return self::constant(self::EXPORT); } public static function import(): self { return self::constant(self::IMPORT); } }
Type-hint against the class, then pass a named instance or build one from a raw value.
function send(ShipmentType $type): void { } send(ShipmentType::import()); // From user input. Throws InvalidArgumentException for an unknown value. send(ShipmentType::fromValue(5)); // 5 (int) ShipmentType::import()->value(); // "5" (string) ShipmentType::import(); // true ShipmentType::fromValue(5) === ShipmentType::import();
Contracts
| Interface | Implementation | Purpose |
|---|---|---|
ConstantValueClassInterface |
ConstantValueClassTrait |
value(), fromValue() and __toString() for the implementing class. |
Namespaces are relative to WebServCo\ConstantValueClass\.
Notes
Only int and string constants count as values. fromValue() uses a strict comparison, so fromValue('5') throws when the constant is 5.
Each value has only one instance per script run. That's why === works. An instance restored from a serialized session is a different object, though, so compare value() there.
Development
# Lint, code style, static analysis (PHPStan, Phan, PHPMD, Psalm) and unit tests. composer all # Run unit tests. composer test:d