-
Notifications
You must be signed in to change notification settings - Fork 1
Enums
While PHP itself does not offer the possibility of enums like it may be known from Java or C#, Stubbles offer support to emulate them. The implementation is a bit hackish in point of how to create the enum instances and that they are changeable at runtime due to some missing features in PHP, but used correct and with a bit discipline they have a lot of advantages regarding to code clarity, code reuse and maintenance.
To create your own Enum you have to extend stubbles\lang\Enum
:
<?php
namespace my\examples;
use stubbles\lang\Enum;
class ReportCellValueType extends Enum
{
/**
* type of the cell value: string
*
* @var ReportCellValueType
*/
public static $STRING;
/**
* type of the cell value: integer
*
* @var ReportCellValueType
*/
public static $INT;
/**
* type of the cell value: percentage
*
* @var ReportCellValueType
*/
public static $PERCENTAGE;
/**
* static initializer
*/
public static function __static()
{
self::$STRING = new self('STRING', function($value) { return (string) $value; });
self::$INT = new self('INT', function($value) { return number_format($value, 0, ',', '.'); } );
self::$PERCENTAGE = new self('PERCENTAGE', function($value) { return number_format($value, 4, ',', '.') . ' %'; } );
}
/**
* format the value
*
* @param scalar $value
* @return scalar
*/
public function format($value)
{
$func = $this->value;
return $func($value);
}
}
ReportCellValueType::__static();
?>
You need to declare public static properties which will hold the instances of the enum class. Additionally you may add other methods that perform operations specific for the enum. As PHP or the class loader do not provide a static initialization of classes we take care for that ourselves by calling ReportCellValueType::__static();
right after the class. As we use autoload this will only be called once and therefore is almost the same as static initialization.
The instances of the ReportCellValueType
declared above may now be used as follows:
echo ReportCellValueType::$PERCENTAGE->format(5); // displays "5.000 %"
Returns the name of the current enum instance.
Returns the value of the current enum instance.
Each of those static methods should be called directly on the class which extends the net\stubbles\lang\Enum
class:
$instanceList = ReportCellValueType::instances();
$stringCellValueType = ReportCellValueType::forName('STRING');
Returns the instance associated with $name.
Returns the instance associated with $value.
Returns a list of all instances of this enum.
Returns a list of all names of this enum.
Returns a list of all values of this enum.