note 114666 added to language.oop5.late-static-bindings

From: Date: Thu, 20 Mar 2014 05:42:29 +0000
Subject: note 114666 added to language.oop5.late-static-bindings
Groups: php.notes 
Request: Send a blank email to php-notes+get-198984@lists.php.net to get a copy of this message
I have implemented enum using late static binding. <?php interface IEnum { /** * Only concrete class should implement this function that should behave as * an enum. * * This method should return the __CLASS__ constant property of that class * * @return string __CLASS__ */ public static function who(); } abstract class Enum { /** * The selected value for the enum implementation * * @var mixed */ public $value; public function __construct($value) { $this->value = $value; } /** * The factory method that creates the corresponding enum class. * * @param integer $type * @return false|\class */ public static function Factory($type) { if (empty($type)) { return false; } // use of late static binding to get the class. $class = static::who(); if (array_key_exists($type, static::$_enums)) { return new $class($type); } return false; } public function getValue() { return $this->value; } public static function getValues() { return array_keys(static::$_enums); } public function getString() { return static::$_enums[$this->value]; } public function __toString() { return static::$_enums[$this->value]; } } class Fruits extends Enum implements IEnum { public static $_enums = array( 1 => 'Apple' 2 => 'Orange' 3 => 'Banana' ) public static function who() { return __CLASS__; } } // Usage // user input from dropdown menu of fruits list $input = 3; $fruit = Fruits::Factory($input); $fruit->getValue(); // 3 $fruit->getString(); // Banana ?> ---- Server IP: 103.21.58.61 Probable Submitter: 115.241.44.27 ---- Manual Page -- http://php.net/manual/en/language.oop5.late-static-bindings.php Edit -- https://master.php.net/note/edit/114666 Del: integrated -- https://master.php.net/note/delete/114666/integrated Del: useless -- https://master.php.net/note/delete/114666/useless Del: bad code -- https://master.php.net/note/delete/114666/bad+code Del: spam -- https://master.php.net/note/delete/114666/spam Del: non-english -- https://master.php.net/note/delete/114666/non-english Del: in docs -- https://master.php.net/note/delete/114666/in+docs Del: other reasons-- https://master.php.net/note/delete/114666 Reject -- https://master.php.net/note/reject/114666 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198984) next »