Demystifying the Four Principles of Object-Oriented Programming

KolaKachi
This entry is part 3 of 24 in the series PHP Object-Oriented Programming(OOP) Crash Course

In this article, we’re diving into the world of object-oriented programming and unraveling the enigmatic concepts that make it tick. Don’t be put off by the fancy-sounding jargon; encapsulation, abstraction, inheritance, and polymorphism are just words waiting to be your friends in the realm of coding.

Encapsulation: Holding It All Together

Let’s begin with encapsulation, which essentially means putting things inside a capsule. Picture those capsules that hold medicines or the ones that catapult astronauts to the moon. Encapsulation in coding is about grouping related functions within a class, like creating a tidy box to keep everything organized. So, if you have multiple functions doing similar tasks, you can encapsulate them within a class, which makes your code neat and manageable.. In PHP, we often use access modifiers such as public, private, and protected to control access to class members. Here’s an example:

class MyClass {
    private $privateVar;

    public function setPrivateVar($value) {
        $this->privateVar = $value;
    }

    public function getPrivateVar() {
        return $this->privateVar;
    }
}

$obj = new MyClass();
$obj->setPrivateVar(42);
echo $obj->getPrivateVar(); // Outputs 42

In this case, privateVar is encapsulated within the class, and we use public methods to set and get its value.

Abstraction: Embracing the Vague

Abstraction sounds obscure but think of it as embracing vagueness or being less specific. In object-oriented programming, you create what’s known as abstract functions or classes. Abstract classes are like templates for what functions should look like, but they don’t have the actual code. Others who inherit from these abstract classes must define their versions of these functions. It’s a bit like saying, “Here’s the name of the function, but you figure out what it does depending on your needs.” Consider this example:

abstract class Shape {
    abstract public function calculateArea();
}

class Circle extends Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

class Square extends Shape {
    private $side;

    public function __construct($side) {
        $this->side = $side;
    }

    public function calculateArea() {
        return pow($this->side, 2);
    }
}

$circle = new Circle(5);
$square = new Square(4);

echo $circle->calculateArea(); // Outputs the area of a circle
echo $square->calculateArea(); // Outputs the area of a square

In this example, we have an abstract class Shape, and both Circle and Square extend it while providing their implementations of the calculateArea method.

Inheritance: Sharing and Extending

Inheritance, as the name suggests, is like borrowing functionalities. Instead of duplicating the same functions in different classes, you can create a parent class that contains those common functions. Other classes (children) can then inherit these functions. If you need to change how a function works, you do it in one place (the parent class), and it automatically reflects in all the child classes. It’s a fantastic way to save code and keep it consistent. Check out this inheritance example:

class ParentClass {
    protected $sharedProperty;

    public function __construct($value) {
        $this->sharedProperty = $value;
    }

    public function sharedMethod() {
        return $this->sharedProperty;
    }
}

class ChildClass extends ParentClass {
    public function childMethod() {
        return 'Child says: ' . $this->sharedMethod();
    }
}

$parent = new ParentClass('Hello from Parent!');
$child = new ChildClass('Hi from Child!');

echo $parent->sharedMethod(); // Outputs "Hello from Parent!"
echo $child->childMethod();   // Outputs "Child says: Hi from Child!"

The ChildClass inherits the properties and methods of ParentClass and can extend or modify them as needed.

Polymorphism: One Method, Many Faces

Polymorphism enables a single method to have multiple implementations based on the context. In PHP, this is often achieved through method overriding. Here’s a simple example:

class Animal {
    public function speak() {
        return 'Animal makes a sound';
    }
}

class Dog extends Animal {
    public function speak() {
        return 'Dog barks';
    }
}

class Cat extends Animal {
    public function speak() {
        return 'Cat meows';
    }
}

$animals = [new Dog(), new Cat()];

foreach ($animals as $animal) {
    echo $animal->speak() . PHP_EOL;
}

In this example, both Dog and Cat classes inherit from Animal but provide their versions of the speak method. When we call speak() on each object, it behaves differently based on its type.

These practical PHP examples should demystify the four fundamental principles of object-oriented programming. As you delve deeper into coding, you’ll appreciate how these concepts enhance code organization, reusability, and flexibility. Stay tuned for more coding adventures and real-world applications of OOP principles!

Series Navigation<< Transitioning from Procedural to Object-Oriented Programming in PHPUnderstanding Classes and Instantiation in PHP >>

Leave a Reply

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