07- PHP Constants

0
687

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.

Syntax:

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.

Output:
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.

 

Output:

230
231

Summary

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:

 

 

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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