The differences between constants and variables in PHP isn’t enormous but here they are:
A constant cannot be changed once set and constants are global so unlike variables they can be accessed in functions without being passed in.
This behaviour makes constants favourable for config like values i.e API keys, MySQL connection details and other config/options that do not get changed.
Code can also be more understandable with using constants and variables instead of just only variables.
Setting a constant is done with define(), calling the constant does not need the $ before the name:
define("API_KEY", "VTb91foKYo");
echo API_KEY;//VTb91foKYo or
const API_KEY = "VTb91foKYo";
Note that using const means the constant is case sensitive.
define() may be case insensitive depending if the parameter is passed through.
Constant being a global example:
function testFunction()
{
return "https://domain.com/data/people?key=" . API_KEY . "";
}
echo testFunction();//https://domain.com/data/people?key=VTb91foKYo A constant can also be an array:
define('DB_DETAILS', array(
'host' => '127.0.0.1',
'database' => 'table_name',
'username' => 'gary',
'password' => 'DxQvYmhcUo'
));
echo DB_DETAILS['username'];//gary Checking if a constant is defined with the defined() function:
if (defined('API_KEY')) {
echo API_KEY;
}
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…