Development

PHP constants vs variables

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;
}

 

Share
Tags: PHPWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago