PHP Abstract Classes
PHP - What are Abstract Classes and Methods?
An abstract classes are incomplete classes.
A abstract class can contains method implementation and also method declaration. The declared method must be implemented by a child class.
We cannot create a object for an abstract class.
Whenever a parent class contains named methods, it relies on its child classes to complete the tasks.
A class that has at least one abstract method is considered abstract. The code for an abstract method does not contain any implementation.
With the abstract
keyword, you can create an abstract class or method :
Related Links
Syntax :-
Child class methods must have the same names and access modifiers as the parent class methods when inheriting from an abstract class. So, if the abstract method is protected
, the child class method must be protected or public, but not private
. Determining the type and amount of needed arguments must also be identical. The child classes, on the other hand, may also accept optional arguments.
As a result, we have the following restrictions when a child class inherits from an abstract class :
- Similarly, the abstract method of the child class must be re-declared in the child class method.
- The access modifier for the child class method must be the same or less limited.
- The amount of arguments necessary must remain constant. Optional parameters can be added to the child class, though.
Example :-
name = $name;
}
abstract public function intro();
}
// Child classes
class Audi extends Car {
public function intro() {
echo "
Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() {
echo "
Proud to be Swedish! I'm a $this->name!";
}
}
// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->intro();
$volvo = new volvo("Volvo");
echo $volvo->intro();
?>
Output :-
Proud to be Swedish! I'm a Volvo!
Example Explained :-
The Car class is passed down to the Audi and Volvo classes. Because of inheritance,
the public $name field and the public __construct()
function from the Car class are
available to the Audi and Volvo classes.
The intro()
method must be implemented because it is an abstract method that should be
defined in all child classes.
Related Links