General Polymorphism with PHP examples

前端 未结 3 698
情深已故
情深已故 2020-12-07 14:54

As only Dogs can play \"fetch\", is this example a good or a bad idea? I suspect it\'s a really bad idea due to the usage of instanceof, but I\'m not entirely sure why.

3条回答
  •  情深已故
    2020-12-07 15:28

    Almost the same as you Krishnadas, Brad. This article helped me alot in understanding how to handle polymorphism in PHP

    http://code.tutsplus.com/tutorials/understanding-and-applying-polymorphism-in-php--net-14362

    interface shape_drawer{
        public function draw(Shape $obj);
    }
    
    class circle implements shape_drawer{
        public function draw(Shape $obj){
            echo "Drawing Circle, Area: {$obj->area} 
    "; } } class square implements shape_drawer{ public function draw(Shape $obj){ echo "Drawing Square, Area: {$obj->area}
    "; } } class triangle implements shape_drawer{ public function draw(Shape $obj){ echo "Drawing Triangle, Area: {$obj->area}
    "; } } class shape_factory{ public static function getShape(){ $shape = $_REQUEST['shape']; if(class_exists($shape)) { return new $shape(); } throw new Exception('Unsupported format'); } } class Shape{ public function __construct($area){ $this->area = $area; } public function draw(shape_drawer $obj) { return $obj->draw($this); } } $shape = new Shape(50); try { $drawer = shape_factory::getShape(); } catch (Exception $e) { $drawer = new circle(); } echo $shape->draw($drawer);

提交回复
热议问题