Abstract classes in php are only for inheriting in other class.
As we know that abstract functions are those functions of abstract class which is only defined. It will be declared in your child class. You can create any method abstract using keyword abstract. You can only create abstract method either in abstract class or interface. Following is example of the abstract method implementation:
In class abc we have defined an abstract function f1. Now when we have inherited class abc then declared function f1. If you have an abstract method in your abstract class then once you inherit your abstract class then it is necessary to declare your abstract method. If you will not declare your abstract method then PHP will throw error in that case.
You can declare your abstract method in child class with the same visibility or less restricted visibility.
In above code you can see that you have declare 3 function in abstract class. But private declaration of the abstract method will always throw error. Because private method is availabe only in the same class context. But in case of f1. This is protected. Now in child class we have defined it as public because public is less restricted than protected. And for function f2 which is already public so we have defined it as public in our child class. We have defined it public because no any visibility is less restricted than public.
An abstract class is a class with or without data members that provides some functionality and leaves the remaining functionality for its child class to implement. The child class must provide the functionality not provided by the abstract class or else the child class also becomes abstract.
Objects of an abstract and interface class cannot be created i.e. only objects of concrete class can be createdTo define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }
In the above example, the method getPrice() in class Furniture has been declared as Abstract. This means that its the responsibility of the child class to provide the functionality of getPrice(). The BookShelf class is a child of the Furniture class and hence provides the function body for getPrice().
Private methods cannot be abstract
If a method is defined as abstract then it cannot be declared as private (it can only be public or protected). This is because a private method cannot be inherited.
abstract class BaseClass {private abstract function myFun();
}
class DerivedClass extends BaseClass {public function myFun() {//logic here }}
$d = new DerivedClass(); //will cause error
Trending Tutorials