Tuesday , 16 July 2019
Home / Programming / PHP / Constants – PHP OOP Tutorial

Constants – 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/ 

Constants are variables that don’t change value during the lifetime of a program. Defining constants in classes are a bit different than defining constants outside of a class.

Defining Constants

In our CanadianPet class, add this bit of code.

To define a constant, we use the const keyword. We then follow it by the name of the constant and it’s value. You’ll notice we omit the $ from the name of the constant property. We don’t need this when we create constants.

We’re going to allow users to grab the price for our pet. Prices for pets may vary, but all prices are taxed by 10%. Let’s create the method for grabbing the price.

As you can see, we’re using the scope resolution operator to help us grab the constant from our class. We MUST use the scope resolution operator if we want to grab constants from our class. Our constant is in the CanadianPet class, but not in the Pet class. For this reason, we use self instead of parent. The self keyword refers to the class itself.

Remember that the scope resolution operator is formatted by CLASSNAME::PROPERTYORMETHOD. We could do something like this.

The only problem is that users can extend this class and may want to use their own version of the constant TAX. So, switch back to self.

Even though constants can only be 1 value for the entire program. They can change values if a class extends a class with a constant.  So, if you extend CanadianPet, then you change the constant of TAX.

Let’s use this function now. In your index.php file, update your code to this.


By using a constant, you can make your program run more efficient by defining a variable that has no loss. You can learn more about constants by going 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.