# PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. By convention, constant identifiers are always uppercase.

---

## 1. Using `define()`
The `define()` function allows you to define constants at runtime.

```php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
```

*   **Scope:** Constants defined with `define()` are global and can be used anywhere in the script.

## 2. Using `const` Keyword
The `const` keyword allows you to define constants at compile time. This is often used inside classes, but can be used in the global scope as well.

```php
const MY_CAR = "Volvo";
echo MY_CAR;
```

## 3. `define()` vs `const`

| Feature | `define()` | `const` |
| :--- | :--- | :--- |
| **Time of Definition** | Runtime | Compile time |
| **Scope** | Global | Global or Class/Namespace |
| **Conditionals** | Can be used inside `if` blocks | Cannot be used inside `if` blocks |

### Example: Conditional Definition
```php
if (!defined('DEBUG')) {
    define('DEBUG', true); // Works
}

// if (...) { const DEBUG = true; } // Syntax Error
```

## 4. Magic Constants
PHP provides a large number of predefined constants to any script which it runs. These change depending on where they are used.

*   `__LINE__`: The current line number of the file.
*   `__FILE__`: The full path and filename of the file.
*   `__DIR__`: The directory of the file.
*   `__FUNCTION__`: The function name.
*   `__CLASS__`: The class name.
*   `__METHOD__`: The class method name.
*   `__NAMESPACE__`: The name of the current namespace.

[[programming/php/php]] [[programming/php/php-magic-constants]]