PHP Constants
A constant is a name that holds a value, like a variable, but the value can not be changed after it is set. Constants are useful for fixed values like the site name, a tax rate or a version number.
Create a constant
There are two ways: the define() function and the const keyword.
<?php
define("SITE_NAME", "Tutorials Class");
const VERSION = "2.0";
echo SITE_NAME . " " . VERSION;
?>
Output:
Tutorials Class - Output Window
Tutorials Class 2.0
- A constant name does not start with
$. - By convention, names are written in capital letters, with underscores, like
MAX_USERS. - Constant names are case-sensitive.
- A constant is global. You can use it everywhere, even inside functions, without the
globalkeyword. - Once set, you can not change it or delete it.
| define() | const | |
|---|---|---|
| Where to use | Anywhere, even inside an if condition | Only at the top level of a file or class |
| Name | Can be created with a variable name | Must be a fixed name |
| Class constants | No | Yes |
Check and read a constant
<?php
define("MAX_USERS", 100);
var_dump(defined("MAX_USERS"));
var_dump(defined("MIN_USERS"));
echo constant("MAX_USERS");
?>
Output:
Tutorials Class - Output Window
bool(true)
bool(false)
100
defined() checks if a constant exists. constant() gets the value when the name is stored as a string, see What is the constant() function?.
Class constants
<?php
class Math {
const PI = 3.14159;
}
echo Math::PI;
?>
Output:
Tutorials Class - Output Window
3.14159
Magic constants
PHP has some special constants that change their value depending on where you use them. They start and end with double underscore.
| Constant | Value |
|---|---|
| __LINE__ | The current line number of the file |
| __FILE__ | The full path and file name |
| __DIR__ | The folder of the file |
| __FUNCTION__ | The name of the current function |
| __CLASS__ | The name of the current class |
<?php
echo "This is line number " . __LINE__;
?>
Output:
Tutorials Class - Output Window
This is line number 2
Useful built-in constants
PHP_VERSION: the version of PHP.PHP_EOL: a new line character, useful in command line scripts.PHP_INT_MAX: the biggest integer.M_PI: the value of pi.
Next chapter: PHP Operators.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Write a program to print “Hello PHP” using variable |
| Write a program to print a string using echo+variable. |
| Write a program to print two variables in single echo |