๐ŸŽ“ A1Learner
๐Ÿ”

PHP Constants

A constant is a named value that stays the same while a program runs. Constants hold values a program must not change, like a tax rate.

A const constant

The const word names the constant MAX and gives it the value 100. The print line shows the value with no $ sign.

<?php
const MAX = 100;
echo MAX, "\n";

A constant in arithmetic

SECONDS holds the number of seconds in one minute. The total for three minutes comes from multiplying by that constant.

<?php
const SECONDS = 60;
$minutes = 3;
$total = $minutes * SECONDS;
echo $total, "\n";

A constant from define()

define() takes a name and a value here. The constant then prints like any other constant.

<?php
define("GREETING", "Hello");
echo GREETING, "\n";

One value changes, one stays

The variable count changes between the two pairs of lines. The constant LIMIT prints the same value both times.

<?php
const LIMIT = 10;
$count = 1;
echo LIMIT, "\n";
echo $count, "\n";
$count = 2;
echo LIMIT, "\n";
echo $count, "\n";

Example

<?php
const RATE = 10;
$book = 100;
$pen = 50;
echo $book * RATE / 100, "\n";
echo $pen * RATE / 100, "\n";

Key points

  • Constant names are written without a $ sign.
  • Uppercase names are the custom for constants.
  • The const word makes a constant from a name and a value.
  • define() makes a constant too, from a name and a value in its brackets.
  • Once set, a constant keeps that one value until the program ends.

In this example, RATE holds 10 and stands for a tax of 10 in every 100. The book price of 100 gives a tax of 10. The pen price of 50 gives a tax of 5.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

Which line makes a constant named MAX with the value 100?