happy cat image

everdevel

coding

login
NotificationX
  • Currently, only notices of comments are displayed.
  • no comment or please login

constant

You learned about variables earlier. After declaring a variable and assigning it a different value, you can declare another value again. A constant is the opposite of a variable. After assigning a value to another, the value does not change. That is, by default, you use a variable if there is a reason to change a value, and a constant if it should not. To declare a constant, use the define statement.

How to declare a constant

define('constant name','value');

Constant names can be in all lowercase letters, but usually use uppercase letters.
It's a promise between programmers.
Unlike variables, $is not used before it.
Words use underscores(_) between words.
If expressed as $myCar when declaring a variable, the constant is used as MY_CAR.
To output a constant, write only the constant name through the output statement.

Constant output method

echo constant name;

The following example declares a constant and outputs the declared constant.

<?php
    define('MY_CAR','porsche911');
    echo MY_CAR;
?>

Here is the resulting image

php image

So let's test if we really assign a different value and it doesn't really change. The following example shows how to assign a different value to a constant to see the result.

<?php
    define('MY_CAR','porsche911');
    define('MY_CAR','crown');
    echo MY_CAR;
?>

Here is the resulting image

php image

After the initial declaration, the constant was declared again with the same constant name using a different value.
However, a constant does not change its value once declared, so the first declared value is printed.
The first value of define() is a constant name and the second is a constant value. You can also enter a third value, and the role is case sensitive.
Possible values ​​for the third value are true and false.
If you do not enter a value, true is entered by default. true means it is not case sensitive and false means it is case sensitive.
In other words, if you declare a constant name as DISNEY and declare it as true, you can output the constant value as disney.
So let's test it.

<?php
    define('DISNEY','MICKEY', true);
    echo disney;
?>

The above code declares the constant name DISNEY in uppercase, outputs using disney in lowercase, and outputs the value normally.
Here is the resulting image

php image

This time we will test it by entering false as the third value.

<?php
    define('DISNEY','MICKEY', false);
    echo disney;
?>

Here is the resulting image. Constant DISNEY is not recognized because it is case sensitive.

php image

Thank you for visiting. If you have any inquiry or explanation of mistakes, please use the comments below.


    
    

Back to the course

ALL COMMENTS 0

Sort by