Sobes.tech
Junior — Middle

Can you explain what is meant by abstraction in object-oriented programming?

sobes.tech AI

Answer from AI

Abstraction in object-oriented programming is a principle that allows hiding complex implementation details and showing only the necessary interface for interaction with an object. In PHP, this is often implemented through abstract classes and interfaces, which define a set of methods without their specific implementation.

For example, an abstract class Animal might declare a method makeSound(), but not implement it. Concrete classes like Dog or Cat will inherit Animal and implement this method in their own way. This allows working with objects through a common interface without worrying about the implementation details of each.

abstract class Animal {
    abstract public function makeSound();
}

class Dog extends Animal {
    public function makeSound() {
        echo "Woof";
    }
}

class Cat extends Animal {
    public function makeSound() {
        echo "Meow";
    }
}

function playSound(Animal $animal) {
    $animal->makeSound();
}

playSound(new Dog()); // Outputs: Woof
playSound(new Cat()); // Outputs: Meow

Thus, abstraction helps create flexible and extensible systems by separating interface from implementation.