PHP code example of dreamscapes / enumeration

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

    

dreamscapes / enumeration example snippets


define('MYAPP_ANIMAL_HORSE', 0);
define('MYAPP_ANIMAL_DOG', 1);
define('MYAPP_ANIMAL_CAT', 2);
// ...

namespace MyApp;

class Animal
{
  const Horse = 0;
  const Dog = 1;
  const Cat = 2;
}

namespace MyApp;

// Let's extend our Enumeration class
class Animal extends \Dreamscapes\Enumeration
{
  const Horse = 0;
  const Dog = 1;
  const Cat = 2;
}

// So far looks the same, but watch now...

$animal = new Animal; // Raises fatal error (private constructor)

Animal::isDefined('Horse'); // Returns (bool)true
Animal::isDefined('Cow'); // Returns (bool)false

// "Reverse resolution"
$value = Animal::Dog;
echo Animal::getName($value); // prints (string)"Dog"

// Type-hinting
function doSomething(Animal $animal)
{
  // $animal is now an instance of the Animal class
  // that can be easily represented as string
  echo $animal;
}
doSomething(Animal::Horse()); // prints (string)"Horse"

// To get the actual value
$value = $animal->value();
// Or, use the Enumeration::getValue() class method
$value = Animal::getValue($animal);

composer or/bin/phpdoc.php