2

Constants in php

In this article I will show you how the constants in php actually work. I am doing this article in english only for practice.
Something important to mention is that I am doing my php file embedded in a html file. This is because when we are not using big php files, we can embed our code in the html file.

So, unlike variables in php, with constants we don´t need to type a dollar sign before the name of the variable, with constants we type the following sintaxis:

define("NameOfTheConstant", Value);

Where name of the constant is only the name you want to set for your constant and the value es the value of that constant can be either an Integer or a String.

Well, let´s go to have some fun with the following where we can see how we can use either Integer or String at the moment to set an integer in our php script.

Other important thing to keep in mind is that constants are as a kind of global variables in pur php scripts and this is because we can use them anywhere whitin our code.

So, the examples are the following:

<html><head><title>This is a sample</title></head><body><?php
                        define("EXIST", "ONE");
                        define("NOEXIST", "ZERO");

                        $PI = 3.14156;

                        if(isset($PI) == EXIST){
                                echo"The variable PI exists";
                        }else{
                                echo"The variable PI doesn't exist";
                        }
                ?></body></html>

In this case we are using string at the moment to declarate our constants but we can do it witrh integer as well.

<html><head><title>This is a sample</title></head><body><?php
                        define("EXIST", 1);
                        define("NOEXIST", 0);

                        $PI = 3.14156;

                        if(isset($PI) == EXIST){
                                echo"The variable PI exists";
                        }else{
                                echo"The variable PI doesn't exist";
                        }
                ?></body></html>

And in either case the result will be the same:

<html><head><title>This is a sample</title></head><body>

                The variable PI exists
        </body></html>

Or course that if we get ride of the $PI variable the result will change

<html><head><title>This is a sample</title></head><body>

                The variable PI doesn't exist
        </body></html>
Escribe tu comentario
+ 2