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
CSS Overflow Property with ExamplesCSSHow to load a module with configuration in SCSS?SCSSRevisiting variable scope in JavaScriptJavaScriptHow to pass arguments in SCSS function?SCSS$this Keyword in PHPPHPHow to get user’s Browser and Operating Systems information using PHP?PHPDROP DATABASE (remove a database) from PostgresPostgresclip and clip-path properties in CSSCSSHow to Hide HTML elements automatically after few seconds using JavaScript?HTMLWhat is IPS(Intrusion Prevention System), How Does It Work and What are the Detection Types?MiscellaneousWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?MiscellaneousList of social media icon logo color codes in HEXMiscellaneous