General Polymorphism with PHP examples

前端 未结 3 690
情深已故
情深已故 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:35

    Another example for Polymorphism in PHP

        width = $width;
          $this->height = $height;
       }
    
       public function getArea(){
          return $this->width * $this->height;
       }
    }
    
    class Circle implements Shape {
       private $radius;
    
       public function __construct($radius) {
          $this->radius = $radius;
       }
    
       public function getArea(){
    
          return 3.14 * $this->radius * $this->radius;
       }
    }
    
    function calculateArea(Shape $shape) {
       return $shape->getArea();
    }
    
    $square = new Square(5, 5);
    $circle = new Circle(7);
    
    echo calculateArea($square), "
    "; echo calculateArea($circle); ?>

提交回复
热议问题