PHP. OOP. Abstract classes and interfaces

Home » Tutorials » PHP » PHP. OOP. Abstract classes and interfaces
In today lesson we will discuss abstract classes and interfaces in php and talk about difference between it.
Abstract classes are implements with adding key word abstract. Abstract classes can have properties and methods. But unlike simple classes methods in abstract classes have not body. Key concept of abstract methods is you must implement these methods in children classes.

Interface is abstract class, but interface has not got properties. Interface implements with key word interface.

One more key concept is class can extends only one class, but it cant implements several interfaces.

Difference in using interfaces and abstract classes is very “thin” problem. Abstract class unites family classes. For example, you have Car class. And class Ford, Toyota extends from Car class. They have common methods (declared in abstract class).
But if you have got Bike class, it makes no sense to implement, for example, changeOil() method. For such classes you need to use interfaces.

Code lesson (abstract class)
<?php

/**
 *  Абстрактный класс обязует наследуемые от него классы
**  реализовывать все абстрактные методы
 */
abstract class Transport
{

    public $driverName = "Водила"; // свойства не могут быть абстрактными

    abstract function driverSide();
    abstract protected function changeOil(); // метод не может быть private

    // в абстрактном классе могут быть и обычные методы
    public function sayHello() {
        echo "Привет вам из метода";
    }


}

class Car extends Transport {

    public $wheels = 4;

    public function countWheels() {
        echo "У машины " . $this->wheels . " колеса";
    }

    public function driverSide() {
        echo $this->driverName . " сидит за рулем слева";
    }

    public function changeOil() {
        echo "В машине надо обязательно менять масло";
    }

}

class Bike extends Transport {

    public $wheels = 2;

    public function countWheels() {
        echo "У велосипеда " . $this->wheels . " колеса";
    }

    public function driverSide() {
        echo $this->driverName . " просто сидит за рулем";
    }

    public function changeOil() {
        echo "В велосипеде надо обязательно менять масло...Да ладно?";
    }

}

$car = new Car();
$bike = new Bike();

/*Посмотрим на объекты*/
echo "<pre>";
    print_r($car);
echo "</pre>";

echo "<pre>";
    print_r($bike);
echo "</pre>";

$car->countWheels();
echo "<br>";
$bike->countWheels();
echo "<br>";
$car->driverSide();
echo "<br>";
$bike->driverSide();
echo "<br>";
$car->changeOil();
echo "<br>";
$bike->changeOil();
echo "<br>";
$car->sayHello();
echo "<br>";
$bike->sayHello();
Code lesson (interface)
<?php

interface Oilable {
    public function changeOil();
}

interface Doorable {
    public function countDoors();
}

class Car implements Oilable, Doorable {

    public $wheels = 4;

    public function countWheels() {
        echo "У машины " . $this->wheels . " колеса";
    }

    public function changeOil() {
        echo "Пора менять масло";
    }

    public function countDoors() {
        echo "В машине 2 или 4 двери";
    }

}

class Bike {

    public $wheels = 2;

    public function countWheels() {
        echo "У велосипеда " . $this->wheels . " колеса";
    }


}

$car = new Car();
$bike = new Bike();

/*Посмотрим на объекты*/
echo "<pre>";
    print_r($car);
echo "</pre>";

echo "<pre>";
    print_r($bike);
echo "</pre>";

$car->countWheels();
echo "<br>";
$bike->countWheels();
echo "<br>";
$car->changeOil();
echo "<br>";
$car->countDoors();

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This