In This example, I will discuss abstract class php and difference between interface and abstract class in php. If you don't know about it, then this abstract class in oops with example tutorial is for you. From this example you will learn about php abstract class.
PHP 5 introduces abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.
Note : An abstract class can contain abstract as well as non abstract methods.
// Abstract class example in PHP
abstract class ClassName
{
// This is abstract function
abstract public function aAbstractMethod();
// This is not abstract function
public function aNonAbstractMethod()
{
echo "I am learning object oriented programming from codechief";
}
}
A class designed only as a parent from which sub-classes may be derived.
abstract method
is a method that is declared, but contains no implementation.To make a class abstract, add the keyword abstract in front of class and the class name in the class definition. See the below example to understand abstract class.
abstract class Student {
protected $firstName;
protected $lastName;
public function __construct($firstName, $lastName){
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName() {
return $this->firstName;
}
public function getLastName() {
return $this->lastName;
}
abstract protected function getFirstNameAndLastName();
}
class School extends Student {
public function getFirstNameAndLastName() {
return $this->getFirstName().' : '. $this->getLastName();
}
}
$object = new School('Codechief','A Computer Science Portal');
echo $object->getFirstNameAndLastName();
Look here, we created a student class which is a abstract class and its contains two method with constructor. Now we created another class name School class and extends it from student class.
Now we can access all the public or protected data from student class but not private data. Now if you run this tutorial, you will see this below output.
Note : Unlike Java, an abstract class can not be created which does not contains at least one abstract method in PHP. If we run the following example then it will display an error message.
// example to understand that an abstract
// class can not contain an method with
// body in php
abstract class Test{
abstract function foo() {
echo "Parent class data";
}
}
Runtime Errors:
Hope it can help you to understand abstract class perfectly.
#php #class #object #oop-php