Задать вопрос
Ответы пользователя по тегу ООП
  • В чем профит ООП?

    В объектно-ориентированном программировании есть очень много полезных вещей.
    Например наследование.
    // describe interfate of engine
    interface IEngine {
      public function getAcceleration();
      public function getPower();
    }
    
    // abstract implementation of engine
    abstract class Engine implements IEngine {
    
      /**
       * Engine acceleration
       */
      protected $_acceleration = 0;
    
      /**
       * Engine power (h/p)
       */
      protected $_power = 0; 
    
      public function getAcceleration() {
        return (int) $this->_acceleration;
      }
    
      public function getPower() {
        return (int) $this->_power;
      }
    }
    
    // extending from engine implementation
    class V12 extends Engine{
      protected $_acceleration = 0.0005;
      protected $_power = 300; 
    }
    
    // describe interface of the car
    interface ICar {
      public function setEngine(IEngine $engine);
      public function accelerate();
    }
    
    // abstract implementation of engine
    abstract class Car {
    
      /**
      * Engine of the car
      * @var IEngine
      */
     protected $_engine;
    
     /**
      * Speed of the car
      * @var Float
      */
     protected $_speed = 0;
    
     public function setEngine(IEngine $engine){
      $this->_engine = $engine;
     }
    
     public function accelerate() {
      if( ! ($this->_engine instanceof IEngine)){
        throw new Exception("Wrong type of engine");
      }
    
      $this->_speed += $this->_engine->getAcceleration();
     }
    } 
    
    class MyCar extends Car {
     public function __construct(){
       $this->setEngine(new V12());
     }
    }
    
    $car = new MyCar();
    $car->accelerate();
    Ответ написан
    Комментировать