Tuesday , 18 June 2019
Home / Programming / PHP / Constructor Method – PHP OOP Tutorial
Constructor Method
Constructor Method

Constructor Method – PHP OOP Tutorial

This tutorial is a part of the PHP OOP tutorial series. If you would like to view the complete list of tutorials under this series and the order you should follow, then click here. http://jaskokoyn.com/php-oop-tutorial-series/ 

It’s always good practice to have things set up when someone creates an instance of your class instead of calling a bunch of functions to do so. Users should only have to call set methods when they need to update or change some properties in your class. The constructor method is the perfect solution to setting up your class for use.

What is the constructor method?

Whenever someone creates an object of your class, PHP will search for a constructor method to run. If it finds one, then it’ll run that method when an object is created. This is perfect for setting things up.

Open up your pet.class.php file and let’s create a constructor method. Add this bit of code into your class.

You must name your constructor method __construct in your class. PHP will look for this function when someone creates an object out of your class. Let’s make our constructor a little more useful. Let’s update our method to this and create a new property.

We create a property named DOB. This property will hold the time our pet was born. When someone creates an instance of Pet, they have to pass in the name of the pet to create this pet. Let’s take a look at how we would do this. Open up the index.php file and update the code to this.

As you can see, when we create a new Pet, we pass in the name for our pet. This is picked up by our constructor method to use. We then echo out it’s time of birth by using the getDOB() method. We haven’t created this method yet. So, add this method in our Pet class.

Try it out.  You should be able to see the time our pet was created.

Why use constructor methods? As you can already see, we’ve saved our user a couple of lines of code by setting things up in our constructor method. For more advance classes, you may want to use your constructor for connecting to a database or grabbing data from external or internal sources for use later. If you extend a class with a constructor method, then the child class will use it unless it defines it’s own constructor method.


Determine what would best suit your class. Remember that classes should be easy to use if you’re sharing with other developers. It’s up to you on how they should use it. More information about this method can be found by clicking here.

About Jasko Koyn

Check Also

Abstract Classes

Abstract Classes – PHP OOP Tutorial

Today, we’ll be discussing what abstract classes are and how we could use them. There …

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.