Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analyze abstract class in php

i have become a bit confused about abstract class ! i have read more of the post written in stackoverflow and another website but i didn't understand ! so i took a look at my book again but i didn't understand it either . so please analyze the code below step by step :

thanks in advance

<?php
abstract class AbstractClass
{
 abstract protected function getValue();
 public function printOut() {
 print $this->getValue();
 }
}
class ConcreteClass1 extends AbstractClass
{
 protected function getValue() {
 return "ConcreteClass1";
 }
}
class ConcreteClass2 extends AbstractClass
{
 protected function getValue() {
 return "ConcreteClass2";
 }
}
$class1 = new ConcreteClass1;
$class1->printOut();

$class2 = new ConcreteClass2;
$class2->printOut();
?>
like image 672
Mehdi Avatar asked Oct 20 '22 07:10

Mehdi


1 Answers

By definition

'An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method that is declared without an implementation'.

If defined an abstract class, you should extend that class with another. In case of having abstract methods within the abstract class, you should write them in the child class in order to instantiate the child.

Related to the code, that is why when you instantiate the ConcreteClass, the getValue function is 'overwritten' to the pattern, while calling to the printOut method is from the father itself, because It is already written and not overwritten by the child. (See also that method was not abstract, that is why you can also use it from the father class)

like image 184
Marcos Segovia Avatar answered Oct 21 '22 22:10

Marcos Segovia