I have this classic switch, I know that when we are building classes is not a good practice use the switch method, so, how I can rebuild this into a class without using switch but Polymorphism and I would like to understand the approach.
/**
* globals below are holding unique id
* $Franklin['Franklin_id'] ,
* $Granny_Smith['Granny_Smith_id'] ,
* etc etc...
*/
global $Fuji, $Gala, $Franklin, $Granny_Smith;
switch($Apple) {
case 'Fuji':
$Color = 'Yellowish green';
$Size = 'medium';
$Origin = 'Japan';
$Season = 'October - January';
$AppleId = $Fuji['Fuji_id'];
break;
case 'Gala':
$Color = 'yellow';
$Size = 'medium';
$Origin = 'New Zealand';
$Season = 'October - January';
$AppleId = $Gala['Gala_id'];
break;
case 'Franklin':
$Color = 'Well-colored';
$Size = 'medium';
$Origin = 'Ohio';
$Season = 'October';
$AppleId = $Franklin['Franklin_id'];
break;
case 'Granny_Smith':
$Color = 'Green';
$Size = 'medium';
$Origin = 'Australia';
$Season = 'October - December';
$AppleId = $Granny_Smith['Granny_Smith_id'];
break;
}
then I would like to be able to use it something like this
$AppleProps = new getApple('Granny_Smith'); // $AppleProps->Color, etc etc
I'm not complete sure what your IDs mean, but this code gives you an AppleFactory that will "stamp" each new apple with a unique ID.
class AppleFactory {
static $id = 0;
static public function getApple($className) {
$apple = new $className();
$apple->id = self::$id++;
return $apple;
}
}
class Apple {
public $id;
public $color;
public $size;
public $origin;
public $season;
}
class GrannySmith extends Apple {
public function __construct() {
$this->color = 'Green';
$this->size = 'medium';
$this->origin = 'Australia';
$this->season = 'October - Desember';
}
}
$a = AppleFactory::getApple('GrannySmith');
print_r($a);