
Constants are the basic things that you must understand if you are just learning PHP.
In this article, we will get acquainted and discuss the constants and examples of the program.
Please try the examples yourself, so you understand better.
OK…
Please start.
What is a constant?
Constants like variables. He can save values. But it can't be changed.
Example:
// kita punya konstanta dengan nilai 5
const SEBUAH_NILAI = 5
// lalu kita ubah menjadi 10
SEBUAH_NILAI = 10 // <-- maka akan terjad error di sini
Do not believe?
Let's try:

In that experiment, we create constants with names
SITE_NAME
with values Petanikode
.
Then we try to change the value to
Belajar PHP
, but an error.
Why can it be an error?
Because the nature of constants is so. We cannot change constant values like variables.

When Should We Use Constants?
Constants are usually used to store values that never change.
Example:
const PHI = 3.14;
const API_KEY = "182939812739812478u12ehj1h2u3123h12";
In the real world, value
PHI
will never change. Then for API_KEY
usually we use to access a web service and this value will never change in the program.
So, we can think of ...
... when to use constants and when to use variables.
Bottom line:
If we want to store a value that will never change, then use a constant.
Whereas if the value changes in the program, then use a variable.
How to make constants and examples
In PHP, we can create constants in two ways.
- Using functions
define()
; - Use keywords
const
.
Example:
<?php
// membuat konstanta dengan fungsi define()
define('DB_SERVER', 'localhost');
define('DB_USER', 'petanikode');
define('DB_PASS', 'R4Hasia');
define('DB_NAME', 'belajar');
// membuat konstanta dengan kata kunci const
const API_KEY = "1234";
?>
Constant names are required to use capital letters to be easily distinguished from variables. Although in PHP it uses the dollar symbol (
$
) for variables, we must follow this rule.
Then, how do you retrieve values from constants?
Just like a variable, we just write the name.
Example:
const SITE_NAME = "Petanikode";
echo "Nama situs: " . SITE_NAME;
Pay attention!
We use point (
.
) to combine two strings. Because constants don't use dollars, we can't directly write it like this:echo "Nama situs: SITE_NAME";
To be more stable, try the following program example:
<?php // file: belajar-konstanta.php
// membuat konstanta
define('VERSION', '1.0.0');
const SITE_NAME = "Petanikode";
const BASE_URL = "https://www.petanikode.com";
// cetak nilai konstanta
echo "Site name: " . SITE_NAME . "<br/>";
echo "URL: " . BASE_URL . "<br/>";
echo "Version: " . VERSION . "<br/>";
The result:

Reference: https://www.petanikode.com/php-konstanta/
0 Komentar untuk "Learning PHP: What are Constants?"
Silahkan berkomentar sesuai artikel