Skip to content

define()

Introduction to the define() Function

The define() function in PHP is used to define a constant.

Usage of the define() Function

The define() function accepts up to three arguments:

  • name: The name of the constant.
  • value: The value assigned to the constant.
  • case_insensitive (optional): If set to true, the constant name becomes case-insensitive. The default is false.

Example Usage of the define() Function

Here is an example of how the define() function can be used in PHP:

Example Usage of the define() Function

php
<?php
define("GREETING", "Hello, world!");
echo GREETING;
?>

In this example, the define() function creates a constant named GREETING with the value Hello, world!. The constant is then output using its name.

Notes on Constants

  • Constant names should follow standard PHP naming conventions (typically uppercase letters, numbers, and underscores).
  • Constants defined with define() are global in scope and can be accessed from anywhere in the script.
  • Use the defined() function to safely verify whether a constant exists before using it: if (defined("GREETING")) { echo GREETING; }

Conclusion

The define() function provides a straightforward way to create constants in PHP. Combined with defined(), it allows for safe and flexible constant management throughout your code.

Practice

In PHP, how is the 'define' function used?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.