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.
In our CanadianPet class, add this bit of code.
const TAX = 0.1;
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.
public function getPetPrice( $price )
return $price + ( $price * self::TAX );
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.
$jack = new CanadianPet( 'Jack' );
echo $jack->getPetPrice( 10 );
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.