PHP Variables
PHP Variables Interview with follow-up questions
1. What are PHP variables and how are they declared?
PHP variables are containers for storing data values. They are declared by prefixing the variable name with a dollar sign ($). PHP is dynamically typed — the type is inferred from the assigned value and can change.
$name = 'Alice'; // string
$age = 30; // int
$price = 9.99; // float
$isActive = true; // bool
$tags = ['php', 'web']; // array
$user = null; // null
Key rules:
- Variable names are case-sensitive:
$nameand$Nameare different. - Names must start with a letter or underscore, not a digit.
- No explicit type declaration is required (though type hints on function parameters and return values are strongly recommended in modern PHP).
Scope: Variables are function-scoped by default. A variable defined outside a function is not automatically visible inside it — you must use the global keyword or pass it as an argument. Static variables retain their value between function calls.
function counter(): int {
static $count = 0;
return ++$count;
}
PHP 8.x typed properties: In class definitions, properties can have declared types that are enforced at runtime:
class User {
public function __construct(
public readonly string $name,
public int $age,
) {}
}
Constructor promotion (PHP 8.0+) declares and assigns properties in the constructor signature directly.
Follow-up 1
Can you explain the scope of PHP variables?
The scope of a variable determines where it can be accessed in a PHP script. PHP has several types of variable scopes:
Global scope: Variables declared outside of any function or class have global scope and can be accessed from anywhere in the script.
Local scope: Variables declared inside a function have local scope and can only be accessed within that function.
Static scope: Static variables are declared inside a function but retain their value between function calls.
Class scope: Variables declared within a class have class scope and can be accessed using the class name followed by the scope resolution operator (::).
Object scope: Variables declared within an object have object scope and can be accessed using the object name followed by the arrow operator (->).
Follow-up 2
What are the different types of variables in PHP?
PHP supports several types of variables:
String: A sequence of characters, enclosed in single quotes ('') or double quotes ("").
Integer: A whole number without a decimal point.
Float: A number with a decimal point.
Boolean: Represents either true or false.
Array: A collection of values.
Object: An instance of a class.
Null: Represents a variable with no value assigned.
Resource: A reference to an external resource, such as a database connection or file handle.
Follow-up 3
How can you check the type of a variable in PHP?
To check the type of a variable in PHP, you can use the gettype() function. It returns a string representing the type of the variable. For example:
$age = 25;
echo gettype($age); // Output: integer
$name = 'John';
echo gettype($name); // Output: string
$price = 9.99;
echo gettype($price); // Output: double
$is_admin = true;
echo gettype($is_admin); // Output: boolean
$colors = ['red', 'green', 'blue'];
echo gettype($colors); // Output: array
$person = new stdClass();
echo gettype($person); // Output: object
Follow-up 4
What is the difference between local and global variables in PHP?
The main difference between local and global variables in PHP is their scope:
Local variables are declared inside a function and can only be accessed within that function. They are not accessible outside of the function.
Global variables are declared outside of any function and can be accessed from anywhere in the script, including inside functions.
It is generally recommended to use local variables whenever possible, as they help encapsulate data and prevent naming conflicts. Global variables should be used sparingly, as they can make code harder to understand and maintain.
2. How can you define a constant in PHP?
PHP provides two ways to define constants:
1. define() function (runtime definition)
define('MAX_UPLOAD_SIZE', 10 * 1024 * 1024); // 10 MB
define('APP_ENV', 'production');
echo MAX_UPLOAD_SIZE;
define() can be called anywhere in code, including conditionally, and supports array values since PHP 7.
2. const keyword (compile-time definition)
const DB_HOST = 'localhost';
const SUPPORTED_FORMATS = ['jpg', 'png', 'webp'];
const must appear at the top level or inside a class/interface/enum; it cannot be used inside functions or conditional blocks.
Class constants (typed since PHP 8.3):
class Config {
const string VERSION = '2.0.0'; // typed constant, PHP 8.3+
const int MAX_RETRIES = 3;
}
echo Config::VERSION;
Enums as typed constants (PHP 8.1+):
enum Status: string {
case Active = 'active';
case Inactive = 'inactive';
}
Enums are now the preferred way to define a closed set of named values, replacing class constant patterns.
Interview gotcha: Constants defined with const inside a namespace follow the namespace, whereas define() creates a global constant unless you include the namespace in the name string.
Follow-up 1
What is the difference between a variable and a constant in PHP?
In PHP, a variable is a symbol that represents a value that can change during the execution of a script, while a constant is a symbol that represents a value that cannot be changed once it is defined. Variables are declared using the $ sign followed by the variable name, while constants are declared using the define() function.
Follow-up 2
Can you change the value of a constant once it is defined?
No, once a constant is defined in PHP, its value cannot be changed. Attempting to change the value of a constant will result in an error.
Follow-up 3
What is the naming convention for constants in PHP?
In PHP, constants are typically named using uppercase letters and underscores. It is a common convention to use all uppercase letters for constant names to differentiate them from variables. For example, CONSTANT_NAME.
3. What is variable interpolation in PHP?
Variable interpolation (also called string interpolation) is the embedding of variable values directly inside a double-quoted string or heredoc. PHP replaces the variable reference with its value when the string is evaluated.
$name = 'Alice';
$greeting = "Hello, $name!"; // simple interpolation → "Hello, Alice!"
echo $greeting;
$user = ['role' => 'admin'];
echo "Role: {$user['role']}"; // curly brace syntax for complex expressions
$obj = new stdClass();
$obj->title = 'Manager';
echo "Title: {$obj->title}";
Double-quoted vs single-quoted strings:
- Double quotes (
"...") — interpolation occurs; escape sequences like\n,\t,\u{1F600}are processed. - Single quotes (
'...') — no interpolation; only\\and\'are escape sequences. Slightly faster for static strings.
$lang = 'PHP';
echo "I love $lang"; // "I love PHP"
echo 'I love $lang'; // "I love $lang" (literal)
Heredoc and Nowdoc:
- Heredoc (`<<
Follow-up 1
Can you provide an example of variable interpolation?
Sure! Here's an example:
$name = 'John';
echo "Hello, $name!";
Output:
Hello, John!
Follow-up 2
What is the difference between single quotes and double quotes in PHP in terms of variable interpolation?
In PHP, single quotes ('') and double quotes ("") have different behaviors when it comes to variable interpolation:
Single quotes do not perform variable interpolation. If you use a variable within single quotes, it will be treated as a literal string.
Double quotes, on the other hand, perform variable interpolation. Variables within double quotes are replaced with their values.
Here's an example to illustrate the difference:
$name = 'John';
echo 'Hello, $name!'; // Output: Hello, $name!
echo "Hello, $name!"; // Output: Hello, John!
As you can see, the variable $name is treated as a literal string within single quotes, but it is replaced with its value within double quotes.
4. What is the difference between 'isset()' and 'empty()' in PHP?
isset() and empty() are two commonly confused language constructs — understanding their exact behavior is a frequent interview topic.
isset($var)
Returns true if the variable exists and its value is not null. Returns false if the variable is undefined or explicitly set to null. Does not trigger a notice on undefined variables.
$a = 0;
isset($a); // true — $a exists and is not null
$b = null;
isset($b); // false — value is null
isset($c); // false — $c is not defined (no notice)
empty($var)
Returns true if the variable does not exist or its value is considered "falsy". Does not trigger a notice on undefined variables.
Values that empty() treats as empty (returns true): "", "0", 0, 0.0, false, null, [] (empty array), and undefined variables.
$a = 0;
empty($a); // true — 0 is falsy
$b = "0";
empty($b); // true — "0" is falsy
$c = [];
empty($c); // true — empty array
$d = "hello";
empty($d); // false — non-empty string
Key distinction:
| Expression | isset() |
empty() |
|---|---|---|
null |
false |
true |
0 |
true |
true |
"" |
true |
true |
"hello" |
true |
false |
| undefined | false |
true |
Modern alternative: Prefer the null coalescing operator (??) over isset() for providing defaults: $name = $_GET['name'] ?? 'Guest';
Follow-up 1
Can you provide an example where 'isset()' and 'empty()' would return different results?
Sure! Here's an example:
$var = 0;
isset($var); // Returns true, as $var is set and has a value
empty($var); // Returns true, as $var is considered empty (0 is one of the empty values)
In this example, 'isset($var)' returns true because $var is set and has a value (0). However, 'empty($var)' also returns true because $var is considered empty according to the empty() function's definition.
Follow-up 2
What is the 'unset()' function used for in PHP?
The 'unset()' function in PHP is used to destroy a variable. It can be used to remove a specific variable from the current scope, making it no longer accessible.
Here's an example:
$var = 'Hello';
unset($var);
echo $var; // Throws an error: Undefined variable: var
In this example, the 'unset($var)' statement destroys the variable $var, so when we try to echo it afterwards, we get an error because the variable no longer exists.
5. What is a superglobal variable in PHP?
Superglobal variables are built-in PHP arrays that are available in every scope — inside functions, classes, and included files — without needing the global keyword.
| Superglobal | Purpose |
|---|---|
$_GET |
Query string parameters from the URL |
$_POST |
Data submitted via HTTP POST |
$_REQUEST |
Merge of $_GET, $_POST, and $_COOKIE (avoid in most cases) |
$_FILES |
Uploaded file metadata |
$_COOKIE |
Cookies sent by the browser |
$_SESSION |
Session variables stored on the server |
$_SERVER |
Server and execution environment info (IP, headers, paths, etc.) |
$_ENV |
Environment variables |
$GLOBALS |
References to all global variables |
Common interview questions about superglobals:
- Why avoid
$_REQUEST? It merges GET, POST, and cookies, making it ambiguous where data came from — this can lead to security issues if a form expects POST data but GET data can override it. - How do you access a specific header? Via
$_SERVER, e.g.,$_SERVER['HTTP_AUTHORIZATION']or$_SERVER['HTTP_CONTENT_TYPE']. - Are superglobals safe to use directly? No — always validate and sanitize values from
$_GET,$_POST,$_COOKIE, and$_FILESbefore use. Never trust client-supplied data.
PHP 8.4 added support for $_POST and $_FILES with additional HTTP verbs (PATCH, PUT, DELETE) when the Content-Type is application/x-www-form-urlencoded or multipart/form-data.
Follow-up 1
What is the scope of superglobal variables?
Superglobal variables have a global scope, which means they can be accessed from anywhere within a PHP script, including functions, classes, and files. They are automatically available in all scopes without the need for any special declaration or import. However, it is important to note that modifying the values of superglobal variables directly within a function or class method will create a local copy of the variable, and the changes will not be reflected globally.
Follow-up 2
Can you name some superglobal variables in PHP?
Some of the superglobal variables in PHP are:
- $_SERVER: Contains information about server and execution environment.
- $_GET: Contains the values of variables passed to the current script via the URL parameters.
- $_POST: Contains the values of variables passed to the current script via HTTP POST method.
- $_REQUEST: Contains the values of variables passed to the current script via both GET and POST methods.
- $_SESSION: Contains variables that are accessible across multiple pages during a user's session.
- $_COOKIE: Contains variables that are stored on the client's computer.
- $_FILES: Contains information about uploaded files.
- $_ENV: Contains variables from the environment in which the PHP script is running.
Follow-up 3
How can you access superglobal variables?
Superglobal variables can be accessed directly using their names, without the need for any special syntax or function calls. For example, to access the value of a variable in the $_GET superglobal, you can simply use $_GET['variable_name']. Similarly, you can access other superglobal variables like $_POST, $_SERVER, etc. by using their respective names.
Live mock interview
Mock interview: PHP Variables
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.