PHP 7 Constants Notice: Constant already defined LESSON 13

PHP 7 Constants are like variables. The only difference is that they cannot be changed. Once you set a “Constant” you cannot change it. PHP Constants need to hold unique information.

Here are the files from the last lesson.

PHP 7 Constants Basic Example

In this Php 7 Constants example, we are setting a constant called “WELCOME”. After setting the constant, we then echo it out onto the page. Create another file in your website project called constants.php. Insert the following code between the header and footer includes.

<?php/* A CONSTANT WORKS LIKE A VARIABLE BUT CANNOT BE CHANGED ONCE IT IS SET */ 
define("WELCOME", "Welcome to Php7, WE LIKE LEARNING PHP7"); echo WELCOME; ?>

 

Only cool people share!

It should look like this.

constants in php 7

Notice: Constant already defined

If you get, “Notice: Constant already defined” then you are calling in the constant somewhere else on your script. It will look something like this.

notice: constant already defined

Case Sensitive Constants in Php7

If you add the parameter of “true” at the end of a constant then it will make it “case sensitive”. Consider this example. We are using the constant of “ROCKS” and “rocks”. Normally we would not be able to do this but since we used “true” in the second constant we made it case sensitive and can use it.

<?php /* WHEN WE USE THE PARAMETER OF TRUE WE ESTABLISH THAT THE NAME IS CASE SENSITIVE. BY DEFAULT DEFINE USES LOWER CASE */ 
define("ROCKS", "Php7 ROCKS"); 
echo ROCKS; 
define("rocks", "Php7 ROCKS, YEAH", true); 
echo rocks; ?>

 

It will look like this, notice both constants are being called and there are no errors.

case sensitive constants

PHP 7 Constants Are Global

PHP 7 constants are global, meaning that you can use them site wide. Notice below when we use the function. Inside the function we are just using a constant. The function will then echo out the sentence we coded in the constant.

/*
CONSTANTS ARE GLOBAL WHICH MEANS THAT YOU CAN USE THEM THROUGHOUT THE ENTIRE WEBSITE. THE WEBSITES HAVE TO BE TIED TOGETHER WITH "INCLUDES(FILE.PHP)" FOR GLOBALS LIKE THIS TO WORK.

IN THE FOLLOWING EXAMPLE NOTICE THAT WE ARE JUST ECHOING OUT THE CONSTANT IN THE FUNCTION. THE FUNCTION WILL THEN PRINT OUT THE STATMENT DEFINED IN THE CONSTANT
*/

define("PHP7", "I AM A PHP 7 WIZARD");

function wizard() {
echo PHP7;
}
wizard();

 

It would look like this.

php7 constants are global

PHP 7 Constants Notice: Constant already defined LESSON 13 was last modified: March 17th, 2023 by Maximus Mccullough
PHP 7 Constants Notice: Constant already defined LESSON 13

Pages: 1 2 3 Next

Leave a Reply

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