Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 19 / 68

Constants (define / const)

In this lesson you will learn how to create constants in PHP with define and const, so values that must not change are handled safely. This is for anyone searching for "PHP constants define const how to use".

PHP creates constants - values that cannot be changed later - with define() or const. They suit values that stay fixed throughout the program, such as configuration settings.

The sample code creates a constant with define("MAX_SCORE", 100); and refers to it as plain MAX_SCORE, without the $ a normal variable would need. That missing $ is the most visible difference from a variable.

A common stumbling block for beginners is accidentally writing $MAX_SCORE with a $. Remember that constants are always referenced without one. It is also worth knowing that const works inside a class while define only works at global scope.

The similar-looking readonly keyword is used when you want a read-only value that differs per instance. Wanting to pin a value down - configuration settings, API keys - comes up constantly in real projects.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)