Beginner php PHP 15 min read

Constants

Constants

Reserved Variable Names

When crafting PHP applications, it's crucial to avoid certain names when declaring your own variables. These names are reserved because they are used by PHP itself for specific, built-in purposes. For example, some handle data received from web forms or tracking user sessions. You'll encounter these more fully in later sections, but be aware that you cannot use the following names for your own variables: $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_REQUEST, $_SESSION, $_ENV, $_COOKIE, $php_errormsg, $http_response_header, $argc, and $argv. A simple way to remember this is that many of these reserved names don't adhere to the standard lowercase-first letter convention for variable names. Furthermore, the name $this is also off-limits; it holds a special meaning within object-oriented programming, which we's explore in more detail later on.

Introducing Constants

Some values are fundamentally unchanging. Think of the mathematical constant pi (approximately 3.14) or the neutral value on the pH scale (7). In programming, representing these fixed values using a constant is a best practice. Unlike variables, constants are assigned a value during the script's execution, and that value cannot be modified afterward. To visually distinguish constants from variables, PHP uses a naming convention: constants are typically written in all uppercase letters with underscores separating words (e.g., MAX_ITEMS, DEFAULT_TIMEOUT). Importantly, constants are not prefixed with a dollar sign ($), unlike variables.

Built-in PHP Constants

PHP provides several predefined constants that are readily available for use in your code. Here are a few examples:

  • M_PI: Represents the mathematical constant pi (π), approximately equal to 3.14159.
  • M_E: Represents Euler's number (e), approximately equal to 2.71828.
  • PHP_INT_MAX: Represents the largest integer value that the PHP environment can reliably handle. This value will depend on your system's architecture (typically 9223372036854775807 for 64-bit systems).
<?php
// Example using the M_PI constant
$radius = 5;
$area = M_PI * $radius * $radius;
echo "The area of a circle with radius " . $radius . " is: " . $area . "\n";
?>

Defining Your Own Constants

You can also create your own named constants within your PHP scripts. This is accomplished using the define() function. The define() function accepts two arguments: the constant's name (in uppercase snake case) and the value you want to assign to it.

<?php
// Define a custom constant
define("MAX_USERS", 100);

// Use the constant in your code
echo "The maximum number of users allowed is: " . MAX_USERS . "\n";
?>