An abstract class cannot be instantiated. Instead it defines (and, optionally, partially implements) the interface for any class that might extend it.You define an abstract class with the abstract keyword. Here I redefine the ShopProductWriter class I created in the previous post, this time as an abstract class:

<?php
abstract class ShopProductWriter
{    
    protected $products = [];    
    
    public function addProduct(ShopProduct $shopProduct)    {
        $this->products[] = $shopProduct;    
    }
}

You can create methods and properties as normal, but any attempt to instantiate an abstract object in this way will cause an error:

<?php
$writer = new ShopProductWriter();

Error: Cannot instantiate abstract class popp\ch04\batch03\ShopProductWriter

In most cases, an abstract class will contain at least one abstract method. These are declared, once again, with the abstract keyword. An abstract method cannot have an implementation. You declare it in the normal way, but end the declaration with a semicolon rather than a method body. Here I add an abstract write() method to the ShopProductWriter class:

<?php
abstract class ShopProductWriter
{    
    protected $products = [];    
    
    public function addProduct(ShopProduct $shopProduct)    
    {        
        $this->products[]=$shopProduct;    
    }    
    
    abstract public function write();
}

In creating an abstract method, you ensure that an implementation will be available in all concrete child classes, but you leave the details of that implementation undefined.Assume I were to create a class derived from ShopProductWriter that does not implement the write()method, as in this example

<?php
class ErroredWriter extends ShopProductWriter
{
}

PHP Fatal error: Class ErroredWriter contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ShopProductWriter::write) in...

So any class that extends an abstract class must implement all abstract methods or itself be declared abstract. An extending class is responsible for more than simply implementing an abstract method. In doing so, it must reproduce the method signature. This means that the access control of the implementing method cannot be stricter than that of the abstract method. The implementing method should also require the same number of arguments as the abstract method, reproducing any class type hinting.


This post is part of series:

1 - Object Oriented Programming Concept2 - Classes3 - Objects4 - Methods5 - Constructors6 - Arguments and Types7 - Static Methods and Properties8 - Constant Properties9 - Abstract Classes10 - Interfaces11 - Traits
PHP#PHPOOP#OOP

Comments (0)