PHP Constants Tutorial: define() and const Explained
PHP constants let you store values that should never change. See how define() and const work, and when to use each one.


PHP Constants store values that you define in your project and that, as the name suggests, you do not want to be changed. There are 2 different ways to create a constant: define and const. Now let’s look at how they are used and written. By convention, constants are defined in uppercase, but this doesn’t mean they won’t work if you use lowercase. In other words, constants are case-sensitive. If you use constants in uppercase, the code you write will be more readable and understandable. Also, the $ sign is not used when using constants.
define('GENISLIK','100px');
<?php
define('GENISLIK','100px');
echo GENISLIK;
?>
//the output of the above code will be 100px.
You can store values such as int, string, and boolean in constants. However, starting with PHP 7, arrays can also be stored in constants.
<?php define( 'MERKEZ', [0, 0] );
Defining Constants with CONST
PHP offers CONST as an alternative for creating constants. Its usage and syntax are as follows.
const SABIT_ADI = deger;
In the syntax above, right after the const keyword, you define the name of the value you will define as a constant. Then you assign a value to this definition.
<?php
const KDV = 1.18;
$satisFiyati= 100;
$toplamTutar = $satisFiyati * KDV;
echo $toplamTutar; // 118
?>
Let’s store an array in the example below;
<?php
const dizi = ['red','gren','blue'];
?>
IN SHORT ;
- Constants are a feature that stores simple values that cannot be changed within the script you write; also, starting with PHP 7, you can store arrays in constants.
- You can access any constant you want from anywhere.
- You can define constants in 2 ways: with Define and Const.
- If you want to define a constant conditionally, use define() because const will not work.
You can find more detailed information on the official website.
Share it if it helped


