PHP code example of mediagone / types-enums

1. Go to this page and download the library: Download mediagone/types-enums 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/ */

    

mediagone / types-enums example snippets


class Article
{
    public const STATUS_DRAFT = 0;
    public const STATUS_PUBLISHED = 1;
    
    private int $status;
    
    public function changeStatus(int $status) : void
    {
        // We need need to check if the provided status value is valid.
        if (! in_array($status, [Article::STATUS_DRAFT, Article::STATUS_PUBLISHED], true)) {
            throw new LogicException("Invalid status ($status)");
        }
        
        $this->status = $status;
    }
}

$article->changeStatus(Article::STATUS_PUBLISHED); // valid
$article->changeStatus(1); // valid but not safe
$article->changeStatus(2); // invalid (and risky if there is no validity check in the method)


class OtherClass
{
    public const ANOTHER_INT_CONSTANT = 0;
}

$article->changeStatus(OtherClass::ANOTHER_INT_CONSTANT); // valid but senseless

/**
 * @method static ArticleStatus DRAFT()
 * @method static ArticleStatus PUBLISHED()
 */
final class ArticleStatus extends EnumInt
{
    private const DRAFT = 0;
    private const PUBLISHED = 1;
}

ArticleStatus::DRAFT();
ArticleStatus::PUBLISHED();

// Strict comparisons are valid since methods always return the same instance
ArticleStatus::PUBLISHED() === ArticleStatus::PUBLISHED(); // true
ArticleStatus::DRAFT() === ArticleStatus::PUBLISHED(); // false

class Article
{
    private ArticleStatus $status;
    
    public function changeStatus(ArticleStatus $status) : void
    {
        // No check needed because $status is always a valid value.
        $this->status = $status;
    }
}

$article->changeStatus(ArticleStatus::PUBLISHED()); // valid
$article->changeStatus(1); // invalid

final class ArticleStatus extends EnumInt
{
    private const DRAFT = 0;
    private const PUBLISHED = 1;
}

ArticleStatus::PUBLISHED()->value; // 1
ArticleStatus::PUBLISHED()->name; // "PUBLISHED"

$a = unserialize(serialize(ArticleStatus::PUBLISHED()));
$b = ArticleStatus::PUBLISHED();

$a === $b; // false

$serializedValue = ArticleStatus::PUBLISHED()->value;

// restore the enum
$enum = ArticleStatus::from($serializedValue);