sábado, 5 de abril de 2025

Class interface

 // Defining the interface

interface BicycleInterface {

    // Method declarations (no implementations)

    public function changeCadence($newValue);

    public function changeGear($newValue);

    public function speedUp($increment);

    public function applyBrakes($decrement);

    public function printStates();

}






// Implementing the BicycleInterface in a class

class Bicycle implements BicycleInterface {

    private $cadence = 0;

    private $speed = 0;

    private $gear = 1;


    // Implementing methods from BicycleInterface

    public function changeCadence($newValue) {

        $this->cadence = $newValue;

    }


    public function changeGear($newValue) {

        $this->gear = $newValue;

    }


    public function speedUp($increment) {

        $this->speed += $increment;

    }


    public function applyBrakes($decrement) {

        $this->speed -= $decrement;

    }


    public function printStates() {

        echo "Cadence: " . $this->cadence . ", Speed: " . $this->speed . ", Gear: " . $this->gear . "\n";

    }


}


// Example usage

$bicycle = new Bicycle();

$bicycle->changeCadence(50);

$bicycle->changeGear(3);

$bicycle->speedUp(20);

$bicycle->applyBrakes(5);

$bicycle->printStates();  // Outputs: Cadence: 50, Speed: 15, Gear: 3

Clsss Inheritance:

 <?php


// Parent class

class Vehicle {

    public $brand;

    public $model;

    

    // Constructor

    public function __construct($brand, $model) {

        $this->brand = $brand;

        $this->model = $model;

    }


    // Method in parent class

    public function start() {

        echo "The vehicle is starting.\n";

    }

}


// Child class inheriting from the Vehicle class

class Car extends Vehicle {

    public $doors;

    

    // Constructor in child class

    public function __construct($brand, $model, $doors) {

        // Call parent class constructor to initialize properties

        parent::__construct($brand, $model);

        $this->doors = $doors;

    }


    // Method in child class

    public function honk() {

        echo "The car is honking.\n";

    }


    // Overriding the parent method

    public function start() {

        echo "The car is starting.\n";

    }

}


// Creating an instance of the Car class

$car = new Car("Toyota", "Corolla", 4);


// Accessing inherited properties

echo "Brand: " . $car->brand . "\n";  // Outputs: Brand: Toyota

echo "Model: " . $car->model . "\n";  // Outputs: Model: Corolla

echo "Doors: " . $car->doors . "\n";  // Outputs: Doors: 4


// Calling methods

$car->start();  // Outputs: The car is starting.

$car->honk();   // Outputs: The car is honking.


?>