In PHP, you can declare a constant using the `define()` function or the `const` keyword. Constants are similar to variables, except that once they are defined, their value cannot be changed or undefined. This feature makes them particularly useful for values that should remain constant throughout the execution of a script, such as configuration options or fixed numeric values.
The `define()` function is a built-in PHP function that allows you to define a constant. The function takes two primary arguments: the name of the constant and its value. Optionally, you can specify a third argument to make the constant case-insensitive, though this is generally discouraged as it’s not a common best practice.
echo SITE_NAME; // Outputs: Example Site
echo MAX_LOGIN_ATTEMPTS; // Outputs: 5
```
You can also define an array as a constant starting from PHP 7.0:
```
define(“SETTINGS”, [
“host” => “localhost”,
“port” => 3306
]);
echo SETTINGS[“host”]; // Outputs: localhost
```
The `const` keyword provides another way to define constants. Unlike `define()`, `const` is defined at compile time, meaning it’s slightly faster. Additionally, `const` can be used to define constants within classes and namespaces.
echo PI; // Outputs: 3.14
echo GREETING; // Outputs: Hello, World!
```
Using constants within a class:
```
class MyClass {
const VERSION = ’1.0.0’;
echo MyClass::VERSION; // Outputs: 1.0.0
$instance = new MyClass();
echo $instance->getVersion(); // Outputs: 1.0.0
```
1. Configuration Constants: \`\`\`php define(“DB\_HOST”, “localhost”); define(“DB\_USER”, “root”); define(“DB\_PASS”, “password”);
$conn = new mysqli(DB_HOST, DB_USER, DB\_PASS); \`\`\`1. Mathematical Constants: \`\`\`php const E = 2.718; const G = 9.81;
echo “Euler’s Number: “ . E; // Outputs: Euler’s Number: 2.718 echo “Gravity: “ . G . “ m/s^2”; // Outputs: Gravity: 9.81 m/s^2 \`\`\`1. Application Paths: \`\`\`php define(“BASE\_PATH”, “/var/www/html/myapp/”); define(“UPLOADS_PATH”, BASE_PATH . “uploads/”);
echo UPLOADS\_PATH; // Outputs: /var/www/html/myapp/uploads/ \`\`\`
1. PHP Manual – Constants
- [Constants](https://www.php.net/manual/en/language.constants.php)
- [define()](https://www.php.net/manual/en/function.define.php)
- [const](https://www.php.net/manual/en/language.oop5.constants.php)
1. W3Schools – PHP Constants
- [PHP Constants](https://www.w3schools.com/php/php_constants.asp)
In summary, using `define()` and `const` to declare constants in PHP provides a robust way to set immutable values, aiding in maintaining consistency and reducing errors throughout your code. By leveraging these methods, you can ensure that important values remain unaltered, improving the reliability and predictability of your applications.