DEV Community

Cover image for What is Override And Extensions
Code Of Accuracy
Code Of Accuracy

Posted on

What is Override And Extensions

In object-oriented programming, overriding and extensions are common concepts that allow developers to modify or enhance the behavior of existing classes or methods. In this article, we'll explore these concepts in the context of PHP, with examples to demonstrate their usage.

1. Overriding in PHP

Overriding is the process of redefining a method in a subclass that was already defined in the parent class. This allows the subclass to provide its own implementation of the method, which may be different from the parent class.

Consider the following example:

class Animal {
  public function makeSound() {
    echo "The animal makes a sound";
  }
}
Enter fullscreen mode Exit fullscreen mode
class Cat extends Animal {
  public function makeSound() {
    echo "Meow!";
  }
}
Enter fullscreen mode Exit fullscreen mode
$cat = new Cat();
$cat->makeSound(); // Outputs "Meow!"
Enter fullscreen mode Exit fullscreen mode

In this example, we have a base class Animal that defines a makeSound() method. The Cat class extends Animal and overrides the makeSound() method with its own implementation that outputs Meow!.

When we create an instance of Cat and call makeSound(), the overridden implementation in Cat is executed instead of the one in Animal.

2. Extensions in PHP

Extensions, also known as method chaining, is a technique that allows developers to add functionality to an object by chaining method calls together. This can make code more concise and easier to read.

Consider the following example:

class Car {
  private $model;

  public function setModel($model) {
    $this->model = $model;
    return $this;
  }

  public function setColor($color) {
    $this->color = $color;
    return $this;
  }

  public function setYear($year) {
    $this->year = $year;
    return $this;
  }
}

$car = new Car();
$car->setModel("Tesla")
    ->setColor("Red")
    ->setYear(2022);

Enter fullscreen mode Exit fullscreen mode

In this example, we have a Car class with three setter methods that set the model, color, and year properties of the car. Each method returns $this, allowing the methods to be chained together.

When we create a new instance of Car and call the setter methods, we can chain them together to set all three properties in a single line of code.

In PHP, overriding and extensions are powerful techniques that allow developers to modify or enhance the behavior of existing classes or methods. By understanding these concepts and using them effectively, you can write more flexible and maintainable code.

Top comments (0)