Constants
A constant is a name with a value that cannot change. You create it with define, giving the name and the value: define('CLUB', 'Nile Club'). By habit constant names are written in capitals. You use a constant without a dollar sign: echo 'Club: ' . CLUB; Constants suit values that must stay the same through the whole site, such as the club’s name or the largest number of books a member may borrow. If you try to define the same constant again, PHP gives a warning and keeps the first value. Be careful with letter case. The book says that a third argument can make a constant case-insensitive, but in PHP 8 that argument is ignored and gives a warning, so treat constant names as case-sensitive, just like variable names. Never type a real password into a constant in lessons: later we will use invented placeholders only.
1<?php 2define('CLUB', 'Nile Club'); 3echo 'Club: ' . CLUB; 4?>
Club: Nile Club
1<?php 2define('MAX_BOOKS', 5); 3$have = 3; 4echo "You may borrow " . (MAX_BOOKS - $have) . " more"; 5?>
You may borrow 2 more
| Variable | Constant | |
|---|---|---|
| Starts with | $ | no sign |
| Value can change? | yes | no |
| How it is created | $level = 7; | define('LEVEL', 7); |
| Case-sensitive? | yes | yes |
Think of three values on a school site that should be constants (for example the school’s name, the pass mark and the number of days in the week). Write the three define lines on paper and one echo line that prints a sentence with one of them.