PHP Constants

In this lesson, I'm going to show you 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: bool define ( string $name , mixed $value [, bool $case_insensitive = false ] ) This time, let's create a new PHP file called “constants.php”. And add the following code.
  1. <HMTL>
  2. <title>Type Casting</title>
  3. <body>
  4. <?php
  5. $max_length = 230; // set a variable containing a value of 230
  6. define("MAX_LENGTH", 230); //set a Constant Containing a fixed value of 230
  7. echo MAX_LENGTH;
  8.  
  9.  
  10. ?>
  11. </body>
  12. </HTML>
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.
  1. <HMTL>
  2. <title>Type Casting</title>
  3. <body>
  4. <?php
  5. $max_length = 230; // set a variable containing a value of 230
  6. define("MAX_LENGTH", 230); //set a Constant Containing a fixed value of 230
  7. echo MAX_LENGTH;
  8. MAX_LENGTH += 1;
  9. echo MAX_LENGTH;
  10.  
  11. ?>
  12. </body>
  13. </HTML>
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.
  1. <HMTL>
  2. <title>Type Casting</title>
  3. <body>
  4. <?php
  5. $max_length = 230; // set a variable containing a value of 230
  6. define("MAX_LENGTH", 230); //set a Constant Containing a fixed value of 230
  7. echo $max_length;
  8. echo '<br/>';
  9. $max_length += 1;
  10. echo $max_length;
  11.  
  12. ?>
  13. </body>
  14. </HTML>
Output:
230
231
Summary The constants are basically like a variables, and most times we’re going to use variables that you could have the option of changing those. But there are some circumstances, may be 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.

Add new comment