OOP

Abstract Class and Function

Abstract Class and Function

Today we are gonna get in touch with the concept of Abstract class and function in PHP. By the way this post I’m writing in English cause I’m frustrated and lazy today. Basically I do prefer to conduct post in Bengali.

Alright Abstract classes are more likely interface . Interesting thing to know about interfaces they are not class they are just a bunch of names. But  as for Abstract classes they are more like a class , you can define properties, you can inherit them , you don’t need to add all functions to child class unlike interface. Lets look upon some code.

An abstract class defined this fashion:

Alright an example make things clear always. Lets say we have a abstract class named SingerProp

We just added two protected properties and an abstract function here. And name & genre public function here for setting name and genre of a singer. As you can see I’ve added return $this on both of these function which seems pretty worthless, but no I just learned about that return its so useful I’ll just explain it later.

Now lets define our Singer class  which will obviously extends from our abstract class

Here you can see  canScream  function which is from our Abstract class. An abstract method from parent class you must need to adhere to the subclass otherwise PHP will throw error. And within this method we just set a Singer ability.

And finally on details function we just printed details of a singer. Here you can see name and genre these attributes inherits from parent class.

Alright now we are ready to build up a Singer. Lets make two of ’em :

These two lines pretty nicer to look right. I really  like this fashion its called method chaining. This is why we added return $this to our functions it just return an instance.

Lets run it:

And welcome to the abstract world.
Hope you get an overview of abstract class and method. (Full code)

-Thanks

 

 

Share this post
Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *