PHP Class Inheritance

Class inheritance in php

PHP Class Inheritance : Classes can inherit the methods and properties of another class. The class that inherits the methods and properties is called a subclass. The class a subclass inherits from is called the parent class.

Inheritance is achieved using the extends keyword


Example :

 class Animal {

  public $name;

  public function hi() {

    echo "Hi from Animal";

  }

}

class Dog extends Animal {

}



$d = new Dog();

$d->hi();

PHP Visibility

Visibility controls how and from where properties and methods can be accessed.So far, we have used the public keyword to specify that a property/method is accessible from anywhere.

There are two more keywords to declare visibility:

protected : Makes members accessible only within the class itself, by inheriting, and by parent classes.

private :Makes members accessible only by the class that defines them.

Class properties must always have a visibility type. Methods declared without any explicit visibility keyword are defined as public.


PHP Interfaces

An interface specifies a list of methods that a class must implement. However, the interface itself does not contain any method implementations. This is an important aspect of interfaces because it allows a method to be handled differently in each class that uses the interface.

  • The interface keyword defines an interface.
  • The implements keyword is used in a class to implement an interface.

For example, AnimalInterface is defined with a declaration for the makeSound() function, but it isn’t implemented until it is used in a class:

 <?php

interface AnimalInterface {

  public function makeSound();

}



class Dog implements AnimalInterface {

  public function makeSound() {

    echo "Woof! <br />";

  }

}

class Cat implements AnimalInterface {

  public function makeSound() {

    echo "Meow! <br />";

  }

}



$myObj1 = new Dog();

$myObj1->makeSound();



$myObj2 = new Cat();

$myObj2->makeSound();

?>

PHP Abstract Classes

Abstract classes can be inherited but they cannot be instantiated. They offer the advantage of being able to contain both methods with definitions and abstract methods that aren’t defined until they are inherited.

The abstract keyword is used to create an abstract class or an abstract method.


Example:

   <?php

abstract class Fruit { 

  private $color; 

    

  abstract public function eat(); 

    

  public function setColor($c) { 

    $this->color = $c; 

  } 

} 



class Apple extends Fruit {

  public function eat() {

    echo "Omnomnom";

  }

}



$obj = new Apple();

$obj->eat();

?>

Spread the love

Leave a Comment

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