Yogesh Chauhan's Blog

How to define constants in PHP?

in PHP on June 15, 2021

Constants are more likely to be used as identifiers since their values CAN NOT change. The magic constants are a bit different in that sense.

Constant identifiers are case-sensitive but they are always defined in uppercase.

Before PHP 8, that wasn’t the case. If you had used define() function to define constants, they might not be case-sensitive!

The scope of a constant is global.

Rules to define a constant

Constant names are like any other variable names.

A valid constant name would start with a letter or underscore and you can add as many numbers, letters, underscores you want.

This is how you can define constants:

define("SITE", "yogeshchauhan.com");
define("BLOG", "yogeshchauhan.com");

You CAN NOT start a constant name with a number:

define("1SITE", "yogeshchauhan.com");
define("2BLOG", "yogeshchauhan.com");

This is valid but not recommended:

define("__SITE__", "yogeshchauhan.com");
define("__BLOG__", "yogeshchauhan.com");

PHP has magic constants and if in future they use the same name to add magic constant then that might break your code.

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How does @extend rule work in SCSS (Sass)?SCSSThe basics of CSS Box modelCSSWhere is the PHP log file located on Mac OS?PHPSteps to Secure a VPNMiscellaneousLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLHow to modify the latest post array using get_posts() in WordPress?WordPressActions vs. Filters: hooks in WordPressWordPressPHP Variables ScopePHPIs there a CSS parent selector?CSSAll different methods for accessing elements in the DOM using JavaScriptJavaScriptasync function in JavaScriptJavaScriptHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScript