PHP code example of brzez / php-magic-enum

1. Go to this page and download the library: Download brzez/php-magic-enum 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/ */

    

brzez / php-magic-enum example snippets

 php
class OrderStatus extends \MagicEnum\MagicEnum
{
	const CREATED        = 1;
	const COMPLETE       = 2;
	const CANCELLED      = 3;
	const PROCESSING     = 4;

	// easy way to extend with the status (for labels/translations etc)
	public function getLabel()
	{
		$name = strtolower($this->getName());
		return "order_status.${name}";
	}
}
 php
// create new instance:
$status = OrderStatus::PROCESSING();
$status->getValue() // => 4

// type safety
public function setStatus(OrderStatus $status)
{
  $this->status = $status;
}
// safe setter (but less annoying)
public function setStatus($status)
{
  if($status instanceof OrderStatus){
    $this->status = $status;
  }else{
    $this->status = new OrderStatus($status); // this validates if $status is defined in OrderStatus const values
  }
}