PHP5 - OOP - 多态 - 帮我重写这个简单的开关

Luc*_*ofi 3 php oop polymorphism switch-statement

假设我有这个经典的开关,我知道当我们构建类时使用switch方法不是一个好习惯,所以,我如何在不使用switch而是多态的情况下将其重建为一个类,我想了解这种方法.

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

那么我希望能够像这样使用它

$AppleProps = new getApple('Granny_Smith'); // $AppleProps->Color, etc etc
Run Code Online (Sandbox Code Playgroud)

提前谢谢你,希望这可以帮助别人.

亲切的问候

卢卡

KOG*_*OGI 5

如果你真的想为此使用OO,那么你应该做的是创建一个appleFactory类,然后为每种苹果都有单独的类......

class appleFactory
{
    public static function getApple( $name )
    {
        $className = $name.'_apple';

        return new $className( );
    }
}

class fuji_apple
{
    public function __construct( )
    {
        $this->color = 'Yellowish green';
        $this->size = 'medium';
        $this->origin = 'Japan';
        $this->season = 'October - January';
        $this->appleId = $Fuji['Fuji_id']; 
    }
}

class gala_apple
{
    public function __construct( )
    {
        $this->color = 'Yellow';
        $this->size = 'medium';
        $this->origin = 'New Zealand';
        $this->season = 'October - January';
        $this->appleId = $Gala['Gala_id']; 
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它......

$fuji = appleFactory::get( 'fuji' );
$gala = appleFactory::get( 'gala' );
Run Code Online (Sandbox Code Playgroud)