PHP (8.5) Module 2 – Values, variables and types
Variables, constants and printing values
Name PHP variables and constants, choose between const and define(), use magic constants, and inspect any value with var_dump() and get_debug_type().
What you will learn
- Create variables and predict which PHP names are case-sensitive
- Detect an undefined variable from its warning, and check a variable with isset()
- Choose between const and define() for a constant
- Use magic and predefined constants to report where code runs
- Inspect a value's type with var_dump(), var_export() and get_debug_type()
Before you start
What you’ll learn · Before you start
What you will learn
- Create variables and predict which PHP names are case-sensitive
- Detect an undefined variable from its warning, and check a variable with isset()
- Choose between const and define() for a constant
- Use magic and predefined constants to report where code runs
- Inspect a value's type with var_dump(), var_export() and get_debug_type()
Before you start
On this page
A checkout script sets $total = 1180; and later prints $Total. The page shows an empty total, PHP prints one
warning, and the script carries on, because $total and $Total are two different variables and the second was
never given a value.
This lesson names variables and constants the way PHP compares them, chooses between const and define(), uses
the magic constants that say where code is running, and inspects any value with var_dump(), var_export() and
get_debug_type(), so you can always see what a variable really holds.
A variable is a dollar sign and a name, and its case counts
A variable is a name that holds a value. In PHP the name starts with $, then a letter or an underscore, then any
letters, digits and underscores: $name, $heightCm and $_count are valid, $2total is not. = stores a value in
the variable, and a second assignment replaces it. This program makes three variables, prints them, and then makes a
fourth whose name differs from the first only in one capital letter:
<?php
$name = 'Asha';
$age = 29;
$heightCm = 162.5;
echo $name, ' is ', $age, "\n";
printf("%s is %.1f cm tall\n", $name, $heightCm);
$Name = 'Ravi';
echo "$name and $Name are two variables\n";
$age = $age + 1;
echo "Next year $name will be $age\n";
function greet(string $who): string
{
return "Hello, $who\n";
}
class Cart {}
echo GREET($name);
echo get_class(new CART()), "\n"; Output
Asha is 29 Asha is 162.5 cm tall Asha and Ravi are two variables Next year Asha will be 30 Hello, Asha Cart
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php profile.php
$name and $Name held 'Asha' and 'Ravi' at the same time, because the manual defines variable names as
case-sensitive. $age = $age + 1; shows assignment at work: PHP read 29, added 1 and stored 30 in the same variable.
Function and class names follow another rule. GREET($name) called the function declared as greet(), and
new CART() made an object of the class Cart, which get_class() reported with the capitals of its declaration.
PHP accepts both spellings, but write every name exactly as it was declared, so that a search for it finds every use:
| Kind of name | Case-sensitive? | What profile.php showed |
|---|---|---|
| Variables | yes | $name and $Name are two variables |
| Functions | no | GREET() ran greet() |
| Classes | no | new CART() made a Cart |
| Constants | yes | see the constants section below |
Building variable names from data
$$field is a variable variable: A variable whose name is taken from the value of another: with $field = 'city', the name $$field means $city. No search for $city finds such a line, so an array is usually the clearer choice.: with $field = 'city', the line
$$field = 'Pune'; sets $city. A search for $city never finds that line, and a misspelt field name quietly
makes a new variable. Keep values that belong together in an array, $profile['city'] = 'Pune';, which the arrays
module of this track covers.
Checkpoint
Check: Variable names and their case
Reading a variable before it is set gives a warning and null
PHP does not ask you to declare a variable before you use it, so a typo in a name does not stop the script. Here is the checkout bug of the opening, in a few lines:
<?php
$total = 1180;
$items = 3;
echo "Items: $items\n";
echo "Total: $Total\n";
var_dump($Total);
var_dump(isset($total), isset($Total));
$lines[] = 'first line';
var_dump($lines); Output
Items: 3
Warning: Undefined variable $Total in undefined.php on line 7
Total:
Warning: Undefined variable $Total in undefined.php on line 8
NULL
bool(true)
bool(false)
array(1) {
[0]=>
string(10) "first line"
}
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php undefined.php
Line 7 read $Total, which does not exist. PHP printed a warning: A message for a problem PHP can continue past, such as reading an undefined variable. The script goes on after it: an undefined variable, for example, is read as null. More in “Your first PHP script, the CLI and error messages” that names the
variable and the line, used null in its place, and went on. Inside a string null becomes empty text, so Total:
came out with nothing after it. var_dump() on line 8 shows the value PHP used, NULL, after a second warning.
Step through what PHP did with line 7:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- Line 7 runs. Line 7 builds the text "Total: $Total" and needs the value of $Total. PHP needs no declaration of variables, so nothing has checked the name before this moment.
- The name is looked up. PHP looks for $Total among the script's variables. Only $total and $items were set, and variable names are case-sensitive, so $total is a different variable.
- A warning, not an error. PHP prints "Warning: Undefined variable $Total" with the file and the line. A warning reports the problem and lets the script continue.
- null takes its place. The missing variable is read as null. Turned into text, null is an empty string, so nothing will appear where the total should be.
- The line finishes. echo prints "Total: " with nothing after it. Had $Total been set, PHP would have used its value here, the branch beside the warning.
- The script goes on. Line 8 runs next, and the output already holds a wrong total. The warning is the only sign of the typo, which is why it must be read and fixed.
isset() asks the same question without a warning: it returned true for $total and false for $Total. It is
also false for a variable that holds null, so it answers “is there a usable value here?”, not “was this name
ever assigned?”. The last two lines show the case the manual singles out as silent: $lines[] = 'first line'; on an
undefined variable makes a new array, with no warning.
Key idea
An undefined variable is read as null after a warning, and the script keeps running: the output may already be
wrong by the time anyone reads the log.
That makes the warning worth reading as a bug report. Hiding it is the quick fix that looks right and is not:
Silencing the warning with @
echo @$Total; hides the warning and keeps the empty total, and the warning was the only sign of the typo. Fix the
name, or give the variable a value before the line that reads it, and keep warnings visible while you develop.
Checkpoint
Check: Undefined variables and isset()
const and define() both make constants, at different moments
A constant is a name for a value that cannot change while the script runs. It has no $, its name is written in
capitals by convention, and any part of the script can read it. PHP has two ways to make one, and they differ enough
to matter:
<?php
const TAX_RATE = 18;
const LABEL = 'Tax ' . TAX_RATE . '%';
$env = 'dev';
if ($env === 'dev') {
define('DEBUG', true);
}
echo LABEL, "\n";
var_dump(DEBUG);
define('TAX_RATE', 12);
echo TAX_RATE, "\n";
echo tax_rate, "\n"; Output (exit status 255)
Tax 18%
bool(true)
Warning: Constant TAX_RATE already defined, this will be an error in PHP 9 in constants.php on line 14
18
Fatal error: Uncaught Error: Undefined constant "tax_rate" in constants.php:17
Stack trace:
#0 {main}
thrown in constants.php on line 17
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php constants.php
const TAX_RATE = 18; declares a constant at the top level of the file, and const LABEL builds its value from it.
const accepts only a constant expression: A value PHP can work out without running the script: literals, other constants and operators on them, such as 'Tax ' . TAX_RATE . '%'. A const declaration takes only a constant expression, never a variable or a call of a function such as date()., a value PHP can work out from
literals, other constants and operators without running any of your code. define('DEBUG', true) is an ordinary
function call that runs when the script reaches it, so it can stand inside the if and take any value.
The end of the run shows two more rules. define('TAX_RATE', 12) did not change the constant: PHP printed a warning
that this will be an error in PHP 9 and kept 18, and the PHP 8.5 migration guide lists redeclaring a constant as
deprecated. Then echo tax_rate stopped the script with an Error, because constant names are case-sensitive and no
constant called tax_rate exists. Step through the run line by line:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- The compile step. Before the first line runs, PHP compiles the whole file. Every const must stand at the top level and hold a constant expression; a const inside an if would stop the file here, with nothing printed.
- TAX_RATE exists. Line 3 declares TAX_RATE with the value 18. Every later line can read it by its name, with no $ in front.
- LABEL is built. Line 4 joins two strings and TAX_RATE into 'Tax 18%'. Joining literals and constants with . is a constant expression, so const accepts it.
- define() runs in the if. The if on line 7 is true, so line 8 calls define('DEBUG', true). A const could not stand here; define() is an ordinary call and runs only when the script reaches it.
- The name is taken. define('TAX_RATE', 12) finds the name already defined. PHP prints a warning that this will be an error in PHP 9, keeps 18 and goes on.
- The wrong case stops it. echo tax_rate asks for a constant in lower case. Constant names are case-sensitive, so none exists, and PHP throws an Error that ends the script with exit status 255.
Because const is part of the structure of the file, PHP checks it before the first line runs. Inside an if, or
with a variable as its value, the file does not start at all:
PHP (const_in_if.php) · const_in_if.php
<?php
$env = 'dev';
if ($env === 'dev') {
const DEBUG = true;
} Output (exit status 255)
Parse error: syntax error, unexpected token "const" in const_in_if.php on line 5
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php const_in_if.php
PHP (const_from_variable.php) · const_from_variable.php
<?php
$rate = 18;
const TAX_RATE = $rate; Output (exit status 255)
Fatal error: Constant expression contains invalid operations in const_from_variable.php on line 4
Stack trace:
#0 {main}
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php const_from_variable.php
| What differs | const |
define() |
|---|---|---|
| What it is | a declaration | a function call |
| Where it may stand | the top level of a file, or inside a class | anywhere code runs, inside if and functions too |
| Its value | a constant expression | any value, a variable’s included |
| In a class | const RATE = 18; declares a class constant |
not possible |
Use const for values that are fixed when you write the code, which is most of them, and define() only when a
constant must depend on something the script finds out while it runs, such as $env in this example.
Checkpoint
Check: const and define()
Magic constants say where the code is running
Some constants change with the place where you write them. PHP replaces these magic constant: A constant whose value depends on where it is written, such as __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__ or __METHOD__. PHP replaces it with that place's line, file, folder, function or class. with the line, file, function or class they stand in, which makes them useful in log messages:
<?php
function logLine(string $message): void
{
echo __FUNCTION__, ' on line ', __LINE__, ': ', $message, "\n";
}
class Invoice
{
public function total(): int
{
echo __CLASS__, ' and ', __METHOD__, "\n";
return 0;
}
}
logLine('starting');
echo 'File ', basename(__FILE__), ', line ', __LINE__, "\n";
var_dump(__DIR__ === dirname(__FILE__));
(new Invoice())->total();
echo Invoice::class, "\n";
echo '[', __FUNCTION__, "]\n";
echo 'PHP ', PHP_VERSION, ' on ', PHP_OS_FAMILY, "\n";
echo PHP_INT_MAX, ' fits in ', PHP_INT_SIZE, " bytes\n";
echo json_encode(PHP_EOL), "\n"; Output
logLine on line 5: starting File where.php, line 19 bool(true) Invoice and Invoice::total Invoice [] PHP 8.5.11 on Darwin 9223372036854775807 fits in 8 bytes "\n"
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php where.php
| Constant | Holds | In where.php |
|---|---|---|
__LINE__ |
the line it is written on | 5 inside logLine(), 19 at the top level |
__FILE__ |
the full path of the file | where.php, cut down with basename() |
__DIR__ |
the folder of the file | the same as dirname(__FILE__): true |
__FUNCTION__ |
the function it is written in | logLine, and an empty string outside any function |
__CLASS__, __METHOD__ |
the class, and the class with the method | Invoice and Invoice::total |
Invoice::class |
the full name of a class, as text | Invoice |
__DIR__ is the one you will use most: require __DIR__ . '/config.php'; loads a file from the folder of the
current file, whichever folder the script was started from.
The last lines print predefined constants, which PHP sets before your script starts. PHP_VERSION is the version
that runs, 8.5.11 here. PHP_OS_FAMILY names the operating system’s family: Darwin on the Mac this ran on,
Linux or Windows elsewhere. PHP_INT_MAX is the largest whole number PHP can hold, which takes 8 bytes on a
64-bit build, and PHP_EOL is the line ending of the system, which json_encode() wrote out as "\n".
Checkpoint
Check: Magic and predefined constants
Dumping a value shows the type that echo hides
echo turns every value into text, and very different values can print the same text. This program prints five
values with echo, then inspects them three ways:
<?php
$id = '42';
$count = 42;
$price = 42.0;
$paid = true;
$note = null;
echo $id, ' ', $count, ' ', $price, ' ', $paid, ' [', $note, "]\n";
var_dump($id, $count, $price, $paid, $note);
echo get_debug_type($id), ' ', get_debug_type($count), ' ', get_debug_type($price), ' ';
echo get_debug_type($paid), ' ', get_debug_type($note), ' ', get_debug_type(new ArrayObject()), "\n";
echo gettype($id), ' ', gettype($count), ' ', gettype($price), ' ';
echo gettype($paid), ' ', gettype($note), ' ', gettype(new ArrayObject()), "\n";
var_export([$id, $count, $price, $paid, $note]);
echo "\n"; Output
42 42 42 1 [] string(2) "42" int(42) float(42) bool(true) NULL string int float bool null ArrayObject string integer double boolean NULL object array ( 0 => '42', 1 => 42, 2 => 42.0, 3 => true, 4 => NULL, )
Recorded with PHP 8.5.11 (cli) (NTS) on macOS 26 arm64. To run it yourself: php inspect.php
echo printed 42 for the string '42', the integer 42 and the float 42.0, 1 for true, and nothing at all
for null. var_dump() told every one apart: it prints the type, the length of a string and the value. The table
lines up what the run printed:
| Value | echo |
var_dump() |
get_debug_type() |
|---|---|---|---|
'42' |
42 | string(2) "42" |
string |
42 |
42 | int(42) |
int |
42.0 |
42 | float(42) |
float |
true |
1 | bool(true) |
bool |
null |
nothing | NULL |
null |
get_debug_type() names a type the way type declarations write it, and gives a class name for an object:
ArrayObject. The older gettype() says integer, double, boolean, NULL and only object, names kept for
history. In an error message, 'expected int, got ' . get_debug_type($value) reads expected int, got string.
var_export() writes a value as PHP code that you could paste into a script, so the float keeps its .0 and null
appears as NULL.
Key idea
Print for people with echo and printf(); to find out what a variable holds, its type and its exact value, use
var_dump().
Checkpoint
Check: Seeing a value's type
Practise: one line about a person
Write formatProfile() on your own computer
Write formatProfile(string $name, int $age, float $heightCm): string that returns Asha, 29, 162.5 cm for
'Asha', 29, 162.5. Build the text with sprintf(), which works like printf() but returns the text instead of
printing it, and use %.1f for the height. Then run var_dump(formatProfile('Ravi', 41, 170));: it is a string,
and the height reads 170.0 cm, because %.1f always prints one decimal.
Then test yourself on the whole lesson. The questions start with the idea you know least, step up as you answer, and explain every answer at once:
Practice that adapts to you
Practise this lesson
15 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher · Warm-up
Which names are case-sensitive in PHP, and which are not?
Variable names are case-sensitive: $total and $Total are two variables, and reading the one that was never set gives a warning and null. Constant names are case-sensitive as well, since PHP 8.0 removed case-insensitive constants, so TAX_RATE and tax_rate are different names and an unknown constant throws an Error. Function names are not case-sensitive for the letters A to Z, so GREET() runs greet(), and class names are not either, so new CART() makes a Cart. That PHP accepts other spellings is no reason to use them: write every name as it was declared, so that a search finds every use and the code reads the same in every file.
-
Fresher to mid
A legacy config.php sets DB_HOST, DB_NAME and DEBUG with define() inside if and else blocks that test which server the code runs on. A teammate wants to turn every define() into const. What breaks, what do you recommend, and why?
-
Fresher to mid
An invoice page sometimes shows an empty discount, and the log holds "Warning: Undefined variable $discount" for line 58. The page never crashes. Explain what PHP did, how you find the cause, and how you make the next such bug fail loudly.
Key takeaways
- Variable names start with
$and are case-sensitive, so$totaland$Totalare two variables; function and class names are not, yet every name should be written as it was declared. - A variable that was never set is read as
nullafter a warning, and the script goes on;isset()asks the same question without a warning. constdeclares a constant from a constant expression at the top level or in a class, whiledefine()runs when it is reached and takes any value; constant names are case-sensitive, and a constant keeps its first value.- Magic constants such as
__LINE__,__DIR__and__METHOD__take their values from the place they are written, and predefined constants such asPHP_VERSIONandPHP_INT_MAXdescribe the PHP that runs. echoshows a value as text,var_dump()shows its type and exact value,var_export()writes it as PHP code, andget_debug_type()names its type.
Terms in this lesson
- constant expression
- A value PHP can work out without running the script: literals, other constants and operators on them, such as 'Tax ' . TAX_RATE . '%'. A const declaration takes only a constant expression, never a variable or a call of a function such as date().
- magic constant
- A constant whose value depends on where it is written, such as __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__ or __METHOD__. PHP replaces it with that place's line, file, folder, function or class.
- variable variable
- A variable whose name is taken from the value of another: with $field = 'city', the name $$field means $city. No search for $city finds such a line, so an array is usually the clearer choice.
References
- PHP Manual: Variables, basics (The PHP Group (php.net))
- PHP Manual: Variable variables (The PHP Group (php.net))
- PHP Manual: User-defined functions (function names) (The PHP Group (php.net))
- PHP Manual: isset (The PHP Group (php.net))
- PHP Manual: Constants (The PHP Group (php.net))
- PHP Manual: Constants, syntax (The PHP Group (php.net))
- PHP Manual: define (The PHP Group (php.net))
- PHP 8.5 migration guide: deprecated features (The PHP Group (php.net))
- PHP Manual: Magic constants (The PHP Group (php.net))
- PHP Manual: Predefined constants (The PHP Group (php.net))
- PHP Manual: var_dump (The PHP Group (php.net))
- PHP Manual: var_export (The PHP Group (php.net))
- PHP Manual: get_debug_type (The PHP Group (php.net))
- PHP Manual: gettype (The PHP Group (php.net))
- PHP Manual: sprintf (The PHP Group (php.net))
Report a problem with this lesson
Kept only in this browser. Your Learn progress