Hey, coders, hope you’re practicing every day. Learning to code is very tough if you don’t practice. I can teach you all the basics here, but in order to implement these concepts in logic to your programs, you gotta practice man. There’s no alternative to practice. Today we will learn another Basic Concept of Constants in PHP Programming.
In the last article I taught you about variables in PHP, today we will learn about constants. As the name suggests, they remain constant throughout the program. You set their values once, and the value cannot be changed. We will understand a simple PHP program to grasp the concept quickly.
Example Program for Constants in PHP
We are making an example program in PHP, where we will calculate the area of a triangle. We will see the use of Constant and Variable and also the use of define keyword.
<?php define("PI","3.14"); $r=7; echo PI; echo "<br>"; echo "Area is =". (PI*$r*$r); ?>
Here what we did is, we have made a Constant named – PI. See we haven’t used $ symbol while defining our Constant. Since it is not a variable. We use a $ symbol with Variables in PHP. (This is a seriously common mistake by beginners, using $ with constants. So make sure you get your basics right).
We used ‘define’ keyword. Inside Parenthesis, We passed two parameters. First one is the name of our constant. The second parameter is the value for our constant. This means that PI value is now set to 3.14. It won’t be changed in anywhere since it’s a constant. We can use this value anywhere.
Then we made one variable as ‘$r’ as our radius of the circle and initialized its value to 7. Then nothing new was done, we printed the value of our constant PI and remember again, we didn’t use the $ symbol with PI. Then we calculated the area of a circle using PI*$r*$r. As simple as that.
I hope you are clear with this simple yet useful concept of Constants in PHP. If you liked this article, don’t forget to share it on at least one of your favorite social media. And if you want more such articles on PHP and other Programming Languages, Just subscribe to our newsletter as we will be adding tons of article on our PHP Programming for Beginners Series.