Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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().

Free lesson, Pro answers: 10 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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:

profile.php: variables, and names whose case matters PHP · profile.php
<?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

  1. Question 1 of 2 After $name = 'Asha'; and then $Name = 'Ravi';, what does echo $name; print?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Asha

    PHP compares variable names exactly, capitals included. profile.php printed "Asha and Ravi are two variables" for the same two assignments.

  2. Question 2 of 2 A file declares function greet(), a class Cart and sets $greeting = "Hi";. Which line prints a warning?

    Choose one answer.

    A hint

    Which of the three kinds of name is case-sensitive?

    Show the answer: Question 2 of 2

    Answer: echo $Greeting;

    Of the three, only variables are case-sensitive. Functions and classes are found in any case, although the declared spelling is the one to write.

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:

undefined.php: reading $Total, which was never set PHP · undefined.php
<?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:

Interactive · stage by stage What PHP does with line 7 of undefined.php Step through one read of a variable that was never set. Watch where PHP warns and where the script goes on.
What PHP does with line 7 of undefined.php, step 6 of 6. Showing Line 7 reads $Total, The name is looked up, A warning is printed, null is used instead, The line finishes, Line 8 runs. In focus: Line 8 runs.had it been setLine 7 reads $Totalinside "Total: $Total\n"The name is looked uponly $total and $items existA warning is printedE_WARNING with the linenull is used insteadnull as text is emptyThe line finishesit prints "Total: "Line 8 runsthe script does not stop

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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()

  1. Question 1 of 2 $total = 1180; is followed by echo "Total: $Total\n"; and then echo "Done\n";. What happens?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A warning about $Total, then "Total: " with nothing after it, then Done

    An undefined variable gives an E_WARNING and the value null. Inside a string null is empty, so the total is missing from the output, and nothing stops the script.

  2. Question 2 of 2 After $coupon = null; and $total = 0;, which of these returns false?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: isset($coupon)

    isset() answers whether a variable exists and is not null, without a warning. A variable set to 0 or to an empty string still counts as set.

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:

constants.php: const, define() and a second define() PHP · constants.php
<?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:

Interactive · stage by stage How constants.php runs, line by line Step through the run from the compile step to the last line. Watch when each constant comes to exist.
How constants.php runs, line by line, step 6 of 6. Showing PHP compiles the file, Line 3: const TAX_RATE, Line 4: const LABEL, Line 8: define('DEBUG'), Line 14: define again, Line 17: tax_rate. In focus: Line 17: tax_rate.PHP compiles the fileevery const is checked firstLine 3: const TAX_RATETAX_RATE is 18Line 4: const LABELbuilt from TAX_RATELine 8: define('DEBUG')runs because $env is devLine 14: define againa warning; TAX_RATE stays 18Line 17: tax_rateno such constant; an Error

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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:

Two places where const is refused

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()

  1. Question 1 of 2 Where can const DEBUG = true; not stand?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Inside an if block

    const may stand at the top level of a file or in a class. Inside if, loops, functions or try blocks, use define(), which is an ordinary call.

  2. Question 2 of 2 What does const LIMIT = 5; define('LIMIT', 10); echo LIMIT; print on PHP 8.5?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A warning that LIMIT is already defined, then 5

    Once a constant is defined it never changes. A second definition prints "Constant LIMIT already defined, this will be an error in PHP 9", and the old value stays.

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:

where.php: magic constants and predefined constants PHP · where.php
<?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

  1. Question 1 of 2 In where.php, __LINE__ inside logLine() printed 5, although logLine() was called on line 18. Why?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: __LINE__ is the line on which it is written, not the line that called the function

    __LINE__, __FILE__, __FUNCTION__ and the other magic constants report where they are written. To report the caller's line, pass __LINE__ as an argument from the call.

  2. Question 2 of 2 bin/report.php runs require 'config.php'; and fails when it is started from another folder. Which line always loads the config.php next to report.php?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: require __DIR__ . '/config.php';

    __DIR__ equals dirname(__FILE__), the folder of the file it is written in, which where.php confirmed with true.

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:

inspect.php: five values that echo cannot tell apart PHP · inspect.php
<?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

  1. Question 1 of 2 Which call shows whether $x holds '42', 42 or 42.0?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: var_dump($x)

    Text output hides the type. var_dump() and var_export() show it; get_debug_type() names it.

  2. Question 2 of 2 What does get_debug_type(42.0) return?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: float

    get_debug_type() gives int, float, string, bool, null, array, or a class name for an object. inspect.php printed float for 42.0.

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.

  1. Question 1 of 15 Which of these is a valid variable name?

    Choose one answer.

    Show the answer: Question 1 of 15

    Answer: $_total

    After the $, a name starts with a letter or an underscore and goes on with letters, digits or underscores.

  2. Question 2 of 15 What does profile.php print?

    What does this program print? Choose one answer.

    <?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";
    Show the answer: Question 2 of 15

    Answer: it prints

    Asha is 29
    Asha is 162.5 cm tall
    Asha and Ravi are two variables
    Next year Asha will be 30
    Hello, Asha
    Cart

    Variable names are case-sensitive, so $name and $Name are separate. Function and class names are not, and get_class() gives the declared spelling.

  3. Question 3 of 15 A colleague renames the declaration function sendMail() to function SendMail() but leaves the 40 calls written as sendMail(). What happens?

    Choose one answer.

    Show the answer: Question 3 of 15

    Answer: Every call still works, but a search for SendMail no longer finds the calls

    The manual says function names are case-insensitive for A to Z but recommends calling them as declared. Keep one spelling so that code stays searchable.

  4. Question 4 of 15 Which error level does PHP 8 report when a script reads an undefined variable?

    Choose one answer.

    Show the answer: Question 4 of 15

    Answer: E_WARNING

    Since PHP 8.0 an undefined variable is an E_WARNING, and the value read is null.

  5. Question 5 of 15 $lines[] = 'first'; runs on a variable that was never set. What happens?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: PHP creates an array that holds 'first', with no warning

    $name[] = value on an undefined variable creates an array. A typo there is silent, so check such names with care.

  6. Question 6 of 15 An invoice shows an empty total, and the log says Warning: Undefined variable $grandTotal in invoice.php on line 41. What do you check first?

    Choose one answer.

    Show the answer: Question 6 of 15

    Answer: The lines that should set $grandTotal, for a misspelt name such as $grandtotal or a branch that skipped it

    Read the warning as a bug report: which variable, which line. Then find where the value should come from, fix the name or the missing assignment, and run the page again.

  7. Question 7 of 15 Are constant names case-sensitive in PHP 8?

    Choose one answer.

    Show the answer: Question 7 of 15

    Answer: Yes, for every constant a script defines

    PHP 8.0 removed case-insensitive constants, so TAX_RATE and tax_rate are always two names.

  8. Question 8 of 15 Which declaration does PHP accept?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: const LABEL = 'Tax ' . TAX_RATE . '%';

    const takes a value PHP can work out without running your code: literals, other constants and operators. Anything that needs the script to run belongs in define().

  9. Question 9 of 15 DB_HOST must come from an environment variable, which getenv('DB_HOST') reads, so it differs between a laptop and a server. Which line defines it?

    Choose one answer.

    Show the answer: Question 9 of 15

    Answer: define('DB_HOST', getenv('DB_HOST'));

    Use const for values fixed in the code and define() for values the script finds out at run time, such as an environment variable.

  10. Question 10 of 15 What does __FUNCTION__ give outside every function?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: An empty string

    where.php printed [] for '[' . __FUNCTION__ . ']' at the top level of the file.

  11. Question 11 of 15 Inside the method total() of the class Invoice, what does __METHOD__ give?

    Choose one answer.

    Show the answer: Question 11 of 15

    Answer: Invoice::total

    __CLASS__ is the class, __FUNCTION__ the function or method name, and __METHOD__ both, joined with ::.

  12. Question 12 of 15 Which constant gives the largest integer that the running PHP can hold?

    Choose one answer.

    Show the answer: Question 12 of 15

    Answer: PHP_INT_MAX

    Predefined constants describe the PHP that runs: its version, its system, its integer limits and its line ending.

  13. Question 13 of 15 What does echo null; print?

    Choose one answer.

    Show the answer: Question 13 of 15

    Answer: Nothing at all

    echo hides null completely, which is why a value can go missing from output without a sign.

  14. Question 14 of 15 What does var_export(42.0); print?

    Choose one answer.

    Show the answer: Question 14 of 15

    Answer: 42.0

    var_export() prints a value as PHP code that you could paste into a script: 42.0, '42', true, NULL.

  15. Question 15 of 15 if (gettype($price) === 'float') never runs its block, even when $price is 4.5. Why?

    Choose one answer.

    Show the answer: Question 15 of 15

    Answer: gettype() returns 'double' for a float; compare get_debug_type($price) with 'float' instead

    gettype() uses old names: integer, double, boolean, NULL, object. get_debug_type() uses the names of type declarations: int, float, bool, null and the class name.

Interview questions

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. 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.

  2. 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?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  3. 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.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Variable names start with $ and are case-sensitive, so $total and $Total are 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 null after a warning, and the script goes on; isset() asks the same question without a warning.
  • const declares a constant from a constant expression at the top level or in a class, while define() 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 as PHP_VERSION and PHP_INT_MAX describe the PHP that runs.
  • echo shows a value as text, var_dump() shows its type and exact value, var_export() writes it as PHP code, and get_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

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.