What is an Abstract Class in PHP?
In this comprehensive article, we will go deep into the realm of PHP abstract classes. This article will offer you with a full overview of how to utilize abstract classes in your PHP development projects, from comprehending the principles to examining the syntax and implementation. This article will provide you with the knowledge and abilities to successfully work with abstract classes in your code, whether you are a newbie or an experienced developer.
An abstract class contains the declaration of methods but not their definition. It only contains their names. It is the responsibility of the child class to define these methods.
What is an abstract method?
An abstract method is a method of an abstract class that is declared using abstract keywords and does not contain the body. It is defined by the child’s class.
- abstract keyword is used to declare an abstract class or method.
- An abstract class must contains at least one abstract method. However, it can also contains non-abstract methods as well.
Syntax
What are the rules of abstract class in PHP?
- An abstract class must contains at least one abstract method. However, it can contains non-abstract methods as well.
- When a child called inherit the abstract parent class, it must defines the abstract methods of parent class with the same name.
- While defining the asbtract methods in the child class, it should be defined with less restricted access modifier. For instance, if the parent class contains the abstract method having protected access modifier. So, when the child class defines this method, it should keep its access modifier as either protected or public. It cannot set it to private, becasue it is more restricted than the protected.
- The child class defining the abstract method must pass the equal number of arguments as specified in the declration in the parent asbtract class. However, the child class can have optional/extra arguments other than those required.
Example of Abstract class in PHP
Explanation of the above example
name = $name; > abstract public function introduction() : string; > // Child classes defining the parent classes class Honda extends Bike < public function intro() : string < return "I am $this->name!"; > > class Suzuki extends Bike < public function introduction() : string < return "I am $this->name!"; > > // Objects from child classes $honda = new honda("Honda"); echo $honda->introduction(); $suzuki= new suzuki("Suzuki"); echo $suzuki->introduction(); ?>
- In the above example, we create an abstract class Bike that contains an abstract method introduction.
- We create two child classes Honda and Suzuki that extends the abstract class and defines the introduction method.
- We create the objects of these classes and call the introduction method using their objects. The introduction method works according to the implementation given by its corresponding class.
Example of abstract class with extra arguments in method overriding
name = $name; > abstract protected function introduction($model) : string; > // Child classes defining the parent classes class Honda extends Bike < public function intro($model) : string < return "I am $this->name. My model is $model"; > > class Suzuki extends Bike < public function introduction($model, $color=null) : string < return "I am $this->name. My model is $model and color is $color"; > > // Objects from child classes $honda = new honda("Honda"); echo $honda->introduction(); $suzuki= new suzuki("Suzuki"); echo $suzuki->introduction(); ?>
Explanation of the above example
- The basic logic of the above example is like the previous example. However, we pass extra argument to the function in the introduction method of suzuki class.
- As we have define the rule earlier in this tutorial, the access modifier of the child class while implementing the abstract method of the parent class must be less than as specified in the parent class for the declaration of this method. So, both the child classes uses public access modifier to define the introduction method.
- Try to define the function with private access modifier, it will produce an error.
Note: The abstract class does not contain any constructor method. So, we cannot create the instance of an abstract class.
Abstract methods and classes in php
This example will hopefully help you see how abstract works, how interfaces work, and how they can work together. This example will also work/compile on PHP7, the others were typed live in the form and may work but the last one was made/tested for real:
// Define things a product *has* to be able to do (has to implement)
interface productInterface public function doSell ();
public function doBuy ();
>
// Define our default abstraction
abstract class defaultProductAbstraction implements productInterface private $_bought = false ;
private $_sold = false ;
abstract public function doMore ();
public function doSell () /* the default implementation */
$this -> _sold = true ;
echo «defaultProductAbstraction doSell: < $this ->_sold > » . ¶ ;
>
public function doBuy () $this -> _bought = true ;
echo «defaultProductAbstraction doBuy: < $this ->_bought > » . ¶ ;
>
>
class defaultProductImplementation extends defaultProductAbstraction public function doMore () echo «defaultProductImplementation doMore()» . ¶ ;
>
>
class myProductImplementation extends defaultProductAbstraction public function doMore () echo «myProductImplementation doMore() does more!» . ¶ ;
>
public function doBuy () echo «myProductImplementation’s doBuy() and also my parent’s dubai()» . ¶ ;
parent :: doBuy ();
>
>
class myProduct extends defaultProductImplementation private $_bought = true ;
public function __construct () var_dump ( $this -> _bought );
>
public function doBuy () /* non-default doBuy implementation */
$this -> _bought = true ;
echo «myProduct overrides the defaultProductImplementation’s doBuy() here < $this ->_bought > » . ¶ ;
>
>
class myOtherProduct extends myProductImplementation public function doBuy () echo «myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too» . ¶ ;
parent :: doBuy ();
>
>
echo «new myProduct()» . ¶ ;
$product = new myProduct ();
$product -> doBuy ();
$product -> doSell ();
$product -> doMore ();
echo ¶ . «new defaultProductImplementation()» . ¶ ;
$newProduct = new defaultProductImplementation ();
$newProduct -> doBuy ();
$newProduct -> doSell ();
$newProduct -> doMore ();
echo ¶ . «new myProductImplementation» . ¶ ;
$lastProduct = new myProductImplementation ();
$lastProduct -> doBuy ();
$lastProduct -> doSell ();
$lastProduct -> doMore ();
echo ¶ . «new myOtherProduct» . ¶ ;
$anotherNewProduct = new myOtherProduct ();
$anotherNewProduct -> doBuy ();
$anotherNewProduct -> doSell ();
$anotherNewProduct -> doMore ();
?>
Will result in:
/*
new myProduct()
bool(true)
myProduct overrides the defaultProductImplementation’s doBuy() here 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()
new defaultProductImplementation()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()
new myProductImplementation
myProductImplementation’s doBuy() and also my parent’s dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!
new myOtherProduct
myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too
myProductImplementation’s doBuy() and also my parent’s dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!
Also you may set return/arguments type declaring for abstract methods (PHP>=7.0)
declare( strict_types = 1 );
abstract class Adapter
protected $name ;
abstract public function getName (): string ;
abstract public function setName ( string $value );
>
class AdapterFoo extends Adapter
public function getName (): string
return $this -> name ;
>
// return type declaring not defined in abstract class, set here
public function setName ( string $value ): self
$this -> name = $value ;
return $this ;
>
>
?>
The documentation says: «It is not allowed to create an instance of a class that has been defined as abstract.». It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:
abstract class Foo
static function bar ()
echo «test\n» ;
>
>
Here is another thing about abstract class and interface.
Sometimes, we define an interface for a `Factory` and ease out some common methods of the `Factory` through an `abstract` class.
In this case, the abstract class implements the interface, but does not need to implement all methods of the interface.
The simple reason is, any class implementing an interface, needs to either implement all methods, or declare itself abstract.
Because of this, the following code is perfectly ok.
interface Element /**
* Constructor function. Must pass existing config, or leave as
* is for new element, where the default will be used instead.
*
* @param array $config Element configuration.
*/
public function __construct ( $config = [] );
/**
* Get the definition of the Element.
*
* @return array An array with ‘title’, ‘description’ and ‘type’
*/
public static function get_definition ();
/**
* Get Element config variable.
*
* @return array Associative array of Element Config.
*/
public function get_config ();
/**
* Set Element config variable.
*
* @param array $config New configuration variable.
*
* @return void
*/
public function set_config ( $config );
>
abstract class Base implements Element
/**
* Element configuration variable
*
* @var array
*/
protected $config = [];
/**
* Get Element config variable.
*
* @return array Associative array of Element Config.
*/
public function get_config () return $this -> config ;
>
/**
* Create an eForm Element instance
*
* @param array $config Element config.
*/
public function __construct ( $config = [] ) $this -> set_config ( $config );
>
>
class MyElement extends Base
public static function get_definition () return [
‘type’ => ‘MyElement’ ,
];
>
public function set_config ( $config ) // Do something here
$this -> config = $config ;
>
>
$element = new MyElement ( [
‘foo’ => ‘bar’ ,
] );
print_r ( $element -> get_config () );
?>
You can see the tests being executed here and PHP 5.4 upward, the output is consistent. https://3v4l.org/8NqqW
Ok. the docs are a bit vague when it comes to an abstract class extending another abstract class. An abstract class that extends another abstract class doesn’t need to define the abstract methods from the parent class. In other words, this causes an error:
abstract class class1 <
abstract public function someFunc ();
>
abstract class class2 extends class1 <
abstract public function someFunc ();
>
?>
Error: Fatal error: Can’t inherit abstract function class1::someFunc() (previously declared abstract in class2) in /home/sneakyimp/public/chump.php on line 7
abstract class class1 <
abstract public function someFunc ();
>
abstract class class2 extends class1 <
>
?>
An abstract class that extends an abstract class can pass the buck to its child classes when it comes to implementing the abstract methods of its parent abstract class.
An interface specifies what methods a class must implement, so that anything using that class that expects it to adhere to that interface will work.
eg: I expect any $database to have ->doQuery(), so any class I assign to the database interface should implement the databaseInterface interface which forces implementation of a doQuery method.
interface dbInterface public function doQuery ();
>
class myDB implements dbInterface public function doQuery () /* implementation details here */
>
>
$myDBObj = new myDB ()-> doQuery ();
?>
An abstract class is similar except that some methods can be predefined. Ones listed as abstract will have to be defined as if the abstract class were an interface.
eg. I expect my $person to be able to ->doWalk(), most people walk fine with two feet, but some people have to hop along 🙁
interface PersonInterface () /* every person should walk, or attempt to */
public function doWalk ( $place );
/* every person should be able to age */
public function doAge ();
>
abstract class AveragePerson implements PersonInterface () private $_age = 0 ;
public function doAge () $this -> _age = $this -> _age + 1 ;
>
public function doWalk ( $place ) echo «I am going to walk to $place » . PHP_EOL ;
>
/* every person talks differently! */
abstract function talk ( $say );
>
class Joe extends AveragePerson public function talk ( $say ) echo «In an Austrailian accent, Joe says: $say » . PHP_EOL ;
>
>
class Bob extends AveragePerson public function talk ( $say ) echo «In a Canadian accent, Bob says: $say » . PHP_EOL ;
>
public function doWalk ( $place ) echo «Bob only has one leg and has to hop to $place » . PHP_EOL ;
>
>
$people [] = new Bob ();
$people [] = new Joe ();
foreach ( $people as $person ) $person -> doWalk ( ‘over there’ );
$person -> talk ( ‘PHP rules’ );
>
?>