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:


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

This is valid but not recommended:


//NOT VALID
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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
Solution for Xcode 11 Command PhaseScriptExecution failed with a nonzero exit code errorMiscellaneousThe Difference Between the echo and print Commands in PHPPHPHow to get Current Hour, Minute and Second in JavaScript?JavaScriptUse inline if to make a shorter conditional syntax in ReactReactHow to use PHPMailer to send an Email via Gmail SMTP Server?PHPSome interesting HTML Input Attributes to rememberHTMLWordPress: How to access first and random row values from a repeater field in ACF?WordPressWhat is an API?MiscellaneousWhat’s a Strict mode in JavaScript?JavaScriptfor @each loop in SCSSSCSSA Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscellaneousSubquery in PostgresPostgres