07- PHP Constants


This tutorial is all about PHP Constants.

In this lesson, I’m going to show you another type of PHP the importance and to how to use the Constants. In PHP, a Constant is an identifier (name) fro a simple value. As the value cannot be changed, unlike to variable.
A Constant name must start with a letter or underscore and no dollar sign before the constant name. And unlike variables, constants are automatically global across the entire script.

How to set Constants?
In setting a constant, we’re going to use the define() function, and it takes a three parameters: First the parameter is used to define the name of the constant, and the second parameter is used to define the value of the constant and last is optional third parameter specify if set to true, the constant will be case-insensitive, and the default behavior is case-sensitive.


This time, let’s create a new PHP file called “constants.php”. And add the following code.

The code above will give us back 230.and since the MAX_LENGTH is constants we won’t be able to change its value. But we’re going to do some experiments using the code below.

Parse error: syntax error, unexpected T_PLUS_EQUAL in C:\xampp\htdocs\file\constants.php on line 8

Meaning it cannot allow us to do the += because it changes the value of MAX_LENGTH. Instead, we’re going to change the code that looks like as shown below.





The constants are basically like a variable, and most times we’re going to use variables that you could have the option of changing those. But there are some circumstances, maybe you want to be used constants to define a username or password to login in your database and you wanted to find those with the constant because they Shouldn’t’ be changeable though always be the same, and we go edit the file of what we ever need to change them to something different.


Readers might read also:



Looking for more source code? Type your keyword here here!

Previous article06- PHP Variables
Next article08 – PHP Basic File System
Hello Itsourcecoders, welcome to itsourcecode.com. I'm Joken Villanueva, MIT a passionate Blogger, Programmer and a Hobbyist. I started Itsourcecode because I wanted to give back and Share all the learnings and knowledge I've learned in my career and I believe through this website I would be able to help and assist those newbie programmers in enhancing their skills from different programming languages. So let us all help each other by sharing our ideas!


Please enter your comment!
Please enter your name here

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