Monday , 20 November 2017
Home / Programming / PHP / Constants – PHP OOP Tutorial
Constants
Constants

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.

Conclusion

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.

http://php.net/manual/en/language.oop5.constants.php

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 *

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link