1. Go to this page and download the library: Download cuyz/magic-constant library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cuyz / magic-constant example snippets
use CuyZ\MagicConstant\MagicConstant;
class ContractStatus extends MagicConstant
{
protected const ACTIVE = [
self::FORMAT_SERVICE_A => 'active',
self::FORMAT_SERVICE_B => 10,
];
// Others status...
public const FORMAT_SERVICE_A = 'a';
public const FORMAT_SERVICE_B = 'b';
}
// Instead of doing this:
if ($status === 'active' || $status === 10) {
//
}
// You can do this:
if ($status->equals(ContractStatus::ACTIVE())) {
//
}
use CuyZ\MagicConstant\MagicConstant;
/**
* You can declare static methods to help with autocompletion:
*
* @method static Example FOO()
* @method static Example BAR()
* @method static Example FIZ()
*/
class Example extends MagicConstant
{
// Only protected constants are used as keys
protected const FOO = 'foo';
// A key can have multiple possible formats for it's value
protected const BAR = ['bar', 'BAR', 'b'];
// You can use an associative array to declare formats
protected const FIZ = [
self::FORMAT_LOWER => 'fiz',
self::FORMAT_UPPER => 'FIZ',
];
// Using constants for formats is not mandatory
public const FORMAT_LOWER = 'lower';
public const FORMAT_UPPER = 'upper';
}
// As a parameter typehint and/or a return typehint
function hello(Example $example): Example {
//
}
hello(new Example('foo'));
// You can also use constants keys as a static method
hello(Example::BAR());
echo (new Example('foo'))->getValue(); // 'foo'
// You can specify the desired output format
echo (new Example('FIZ'))->getValue(Example::FORMAT_LOWER); // 'fiz'
$constant = new Example('b');
echo $constant->getKey(); // 'BAR'
$constant = new Example('fiz');
echo $constant->getAllFormats(); // [new Example('fiz'), new Example('FIZ')]
$constant = new Example('BAR');
echo $constant->getAllValues(); // ['bar', 'BAR', 'b']
$constant = new Example('BAR');
echo $constant->normalize(); // new Example('bar')
(new Example('foo'))->equals(new Exemple('bar')); // false
(new Example('foo'))->equals(null); // false
(new Example('fiz'))->equals(new Exemple('FIZ')); // true
(new Example('b'))->equals(new Exemple('b')); // true
Example::values();
[
'FOO' => new Example('foo'),
'BAR' => new Example('bar'),
'FIZ' => new Example('fiz'),
];
// You can specify a regex pattern to match certain keys
Example::values('/^F(.+)/');
[
'FOO' => new Example('foo'),
'FIZ' => new Example('fiz'),
];