Beginner Level (0–1 Years)
1. What is the output of the following code: echo 5 + "5 days";
?
Answer:
The output is 10
. PHP performs type juggling in mathematical operations, converting the string "5 days"
to the integer 5
by extracting the leading numeric part and ignoring the non-numeric part (" days"
). Thus, 5 + 5
equals 10
.
2. Can you use a function before it is defined in PHP?
Answer:
Yes, you can call a function before its declaration in PHP because PHP hoists function declarations during the parsing phase, making them available throughout the script. However, this does not apply if the function is defined inside a conditional block that hasn’t been executed.
3. What will this code output: var_dump([] == false);
?
Answer:
The output is bool(true)
. In PHP, an empty array is loosely equal to false
when using ==
due to type juggling. However, using strict comparison ([] === false
) would return bool(false)
because they are different types.
4. How does PHP handle variable names that are case-sensitive?
Answer:
Variable names in PHP are case-sensitive. For example, $name
and $Name
are treated as distinct variables. However, function names and class names are case-insensitive.
5. What’s the difference between include
and require
in PHP?
Answer:
require
produces a fatal error and stops script execution if the file is not found, while include
emits a warning and allows the script to continue. Use require
for critical files and include
for optional ones.
6. Why does isset($var)
return false even though $var = null;
is set?
Answer:
isset($var)
returns false
when $var
is explicitly set to null
because isset()
checks if a variable exists and is not null
. A variable set to null
exists but fails the isset()
check.
7. What is the output of: echo "5" + "5";
?
Answer:
The output is 10
. Both strings ("5"
) are numeric, so PHP converts them to integers during addition, resulting in 5 + 5 = 10
.
8. What is the difference between single quotes ('
) and double quotes ("
) in PHP strings?
Answer:
Double quotes ("
) allow variable interpolation (e.g., echo "$var";
outputs the value of $var
) and interpret escape sequences (e.g., \n
). Single quotes ('
) treat everything literally, so echo '$var';
outputs $var
as text. Single quotes are slightly faster due to less parsing.
9. Is PHP pass-by-reference or pass-by-value?
Answer:
By default, PHP passes arguments by value, meaning a copy of the variable is passed to the function. To pass by reference, use the &
symbol, e.g., function test(&$var)
, allowing the function to modify the original variable.
10. How can you prevent a form from resubmitting on refresh in PHP?
Answer:
Use the Post/Redirect/Get (PRG) pattern. After processing a POST request, redirect the user to a new page using header("Location: thankyou.php");
. This changes the request to a GET, preventing resubmission on refresh.
11. What is the purpose of the htmlspecialchars()
function in PHP?
Answer:
The htmlspecialchars()
function converts special characters (e.g., &
, <
, >
, "
, '
) to their HTML entities (e.g., &
, <
, >
). This prevents cross-site scripting (XSS) attacks by ensuring user input is safely displayed as text, not executed as HTML or JavaScript.
12. What’s the difference between ==
and ===
in PHP?
Answer:
==
performs loose comparison, converting types (type juggling) to compare values. ===
performs strict comparison, checking both value and type without conversion. For example, "5" == 5
is true
, but "5" === 5
is false
.
13. What will this output: echo (int) 10.9;
?
Answer:
The output is 10
. Casting to an integer with (int)
truncates the decimal portion of 10.9
, not rounding it.
14. What is the difference between empty()
and isset()
?
Answer:
isset($var)
checks if a variable exists and is not null
. empty($var)
checks if a variable is considered “empty” (e.g., 0
, ""
, null
, false
, or an empty array). empty()
does not require the variable to exist.
15. How do you loop through an array in PHP?
Answer:
You can loop through an array using foreach
or for
. The foreach
loop is most common, e.g., foreach ($array as $value) { echo $value; }
for values or foreach ($array as $key => $value) { echo "$key: $value"; }
for key-value pairs. A for
loop requires knowing the array’s length, e.g., for ($i = 0; $i < count($array); $i++) { echo $array[$i]; }
.
16. What is the scope of a variable declared inside a function in PHP?
Answer:
A variable declared inside a function has local scope, meaning it is only accessible within that function. To access it outside, return it or use the global
keyword (though globals are generally discouraged).
17. What will echo "Hello" . 5 * 2;
print?
Answer:
The output is Hello10
. The multiplication 5 * 2
is evaluated first due to operator precedence, resulting in 10
. The dot operator (.
) then concatenates "Hello"
with 10
, producing Hello10
.
18. Can you access a private property directly outside the class?
Answer:
No, private properties are only accessible within the class that defines them. Attempting to access them outside the class results in a fatal error. Use public methods (e.g., getters) to access private properties.
19. What’s the difference between echo
and print
?
Answer:
echo
can output multiple strings (e.g., echo $a, $b;
) and is slightly faster. print
only outputs one string and always returns 1
, making it usable in expressions. Both are used to output data.
20. What is the output of strpos("hello", "l")
?
Answer:
The output is 2
. strpos()
returns the 0-based position of the first occurrence of "l"
in "hello"
, which is at index 2.
21. What’s wrong with this: if ($a = 5) { ... }
?
Answer:
It uses assignment (=
) instead of comparison (==
or ===
). This assigns 5
to $a
and evaluates to true
, which is likely not the intended logic. Use if ($a == 5)
for comparison.
22. How do you define a constant in PHP?
Answer:
Use define("CONSTANT_NAME", value);
, e.g., define("PI", 3.14);
. Constants are global, case-sensitive by default, and cannot be redefined once set.
23. Is 0 == "any string"
true or false?
Answer:
It depends. For non-numeric strings (e.g., "hello"
), 0 == "hello"
is true
because the string converts to 0
in loose comparison. For numeric strings (e.g., "123"
), 0 == "123"
is false
because "123"
converts to 123
. Use ===
to avoid type juggling issues.
24. What does the die()
function do?
Answer:
die()
stops script execution and optionally outputs a message, e.g., die("Error occurred");
. It is an alias for exit()
and is often used for error handling.
25. Can you modify a global variable inside a function without global
?
Answer:
No, you cannot directly modify a global variable inside a function without using global $var;
or the $GLOBALS
array (e.g., $GLOBALS['var'] = value;
). Without these, the variable is treated as local to the function.
👋 Need top PHP developers for your project? Interview this week!
Fill out the form to book a call with our team. We’ll match you to the top developers who meet your requirements, and you’ll be interviewing this week!
Intermediate Level (1–3 Years)
1. What will this output: echo true + true + true;
?
Answer:
The output is 3
. In PHP, the boolean true
is cast to 1
and false
to 0
in arithmetic operations. Thus, true + true + true
becomes 1 + 1 + 1 = 3
.
2. What is the difference between self::
and static::
in PHP?
Answer:
self::
refers to the class where the method is defined, while static::
uses late static binding to refer to the class called at runtime. For example:
class ParentClass { static function test() { echo self::class; } }
class ChildClass extends ParentClass { }
ChildClass::test(); // Outputs: ParentClass
class ParentClass2 { static function test() { echo static::class; } }
class ChildClass2 extends ParentClass2 { }
ChildClass2::test(); // Outputs: ChildClass2
3. What does the __construct()
method do?
Answer:
The __construct()
method is a class constructor, automatically invoked when an object is created using new
. It’s used to initialize object properties or set up dependencies.
4. What happens if you declare two methods with the same name in a PHP class?
Answer:
PHP will throw a fatal error, as method overloading based on parameter signatures is not supported. Methods must have unique names within a class.
5. What does the final
keyword do when used on a method?
Answer:
The final
keyword prevents child classes from overriding the method, ensuring its implementation remains unchanged in subclasses.
6. How does PHP handle multiple inheritance?
Answer:
PHP does not support multiple inheritance for classes but allows code reuse through traits, which can be included in classes using the use
keyword.
7. What is the visibility of class constants in PHP?
Answer:
Since PHP 7.1, class constants can have public
, protected
, or private
visibility. Before PHP 7.1, constants were implicitly public.
8. What is a magic method? Give an example.
Answer:
Magic methods start with __
and handle special behaviors. For example, __get($name)
is called when accessing an undefined or inaccessible property, allowing custom logic like returning a default value.
9. How do you handle exceptions in PHP?
Answer:
Use try...catch
blocks to catch exceptions, with optional finally
for cleanup. Multiple catch blocks can handle different exception types:
try {
if (!file_exists('file.txt')) {
throw new Exception('File not found');
}
} catch (InvalidArgumentException $e) {
echo 'Invalid argument: ' . $e->getMessage();
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} finally {
echo 'Cleanup';
}
10. What’s the output of: echo '1' + '2abc';
?
Answer:
The output is 3
. PHP converts both strings to numbers during addition. '1'
becomes 1
, and '2abc'
becomes 2
by taking the leading numeric part, so 1 + 2 = 3
.
11. What are traits in PHP?
Answer:
Traits enable code reuse in PHP where multiple inheritance isn’t supported. Declared with the trait
keyword, they are included in classes using use
. Example: trait Log { function log() { echo 'Logging'; } } class User { use Log; }
.
12. How do you declare an abstract class in PHP?
Answer:
Use the abstract
keyword: abstract class Base { abstract function method(); }
. Abstract classes cannot be instantiated and may include abstract methods (without implementation) that child classes must define.
13. What’s the use of instanceof
in PHP?
Answer:
The instanceof
operator checks if an object is an instance of a specific class, a subclass, or implements an interface, e.g., $obj instanceof MyClass
.
14. Can you serialize a resource in PHP?
Answer:
No, resources (e.g., database connections, file handles) cannot be serialized. When serialized, they are converted to null
, which is important for session storage or data persistence.
15. What’s the difference between GET and POST in PHP?
Answer:
GET appends data to the URL, is visible, bookmarkable, and limited in size. POST sends data in the request body, is more secure for sensitive data, and supports larger data volumes.
16. What is a closure in PHP?
Answer:
A closure is an anonymous function that can capture variables from its surrounding scope using use
, e.g., $func = function($x) use ($y) { return $x + $y; };
.
17. What is the purpose of the interface
keyword in PHP, and how is it used?
Answer:
An interface
defines a contract that classes must follow by implementing all its methods. Declared with interface
, it’s used with the implements
keyword, e.g., interface Logger { public function log($msg); } class FileLogger implements Logger { public function log($msg) { echo $msg; } }
.
18. How would you prevent SQL injection in PHP?
Answer:
Use prepared statements with PDO or MySQLi, binding parameters to avoid direct query concatenation, e.g., $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); $stmt->execute([$id]);
.
19. What’s the difference between public, protected, and private in PHP?
Answer:
public
: Accessible anywhere. protected
: Accessible in the class and its subclasses. private
: Accessible only within the defining class.
20. What’s the purpose of spl_autoload_register()
?
Answer:
It registers a function to automatically load undefined classes or interfaces when they are instantiated, e.g., spl_autoload_register(function($class) { include $class . '.php'; });
.
21. What does the clone
keyword do in PHP?
Answer:
The clone
keyword creates a shallow copy of an object. If a __clone()
method is defined, it’s called after cloning to customize the copy.
22. How does PHP’s garbage collection work?
Answer:
PHP uses reference counting to free memory when objects have no references. A cyclic garbage collector runs periodically to clean up circular references, preventing memory leaks.
23. What’s the difference between array_merge()
and +
for arrays?
Answer:
array_merge()
combines arrays, reindexing numeric keys and overwriting duplicate string keys. The +
operator keeps the first occurrence of duplicate keys, preserving the left-hand array’s values.
24. How can you restrict access to a PHP page to logged-in users?
Answer:
Use sessions to check for a user identifier, e.g., if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; }
, redirecting unauthenticated users to a login page.
25. What is the difference between require_once
and require
?
Answer:
require_once
ensures a file is included only once, preventing redefinition errors. require
includes the file every time it’s called, which may cause errors if classes or functions are redefined.
26. What’s the output: var_dump((bool)"0");
?
Answer:
The output is bool(false)
. In PHP, the string "0"
is considered false when cast to a boolean, unlike other non-empty strings, which are true
.
27. What is type juggling in PHP?
Answer:
Type juggling is PHP’s automatic type conversion during operations, e.g., "5" + 1
becomes 6
as the string is cast to an integer. It can lead to unexpected results, so strict comparison (===
) is often preferred.
28. What are anonymous classes and when would you use them?
Answer:
Anonymous classes, introduced in PHP 7, are defined using new class
. They’re useful for one-off objects, such as mocks in unit testing or temporary implementations, e.g., $obj = new class { public function test() { return 'test'; } };
.
29. How do you implement dependency injection in PHP?
Answer:
Dependency injection passes dependencies (e.g., objects, services) to a class, typically via constructor or setter methods, to promote loose coupling. Example:
class UserService {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
}
30. What does headers_sent()
do?
Answer:
headers_sent()
checks if HTTP headers have been sent to the client, useful before calling header()
or session_start()
to avoid errors if output has started.
31. What is the output: echo 'PHP'[-1];
?
Answer:
The output is P
. Since PHP 7.1, negative string offsets are supported, and -1
accesses the last character of the string 'PHP'
.
32. How do you define a constant array in PHP?
Answer:
Use define('ARR', ['a', 'b']);
for global constants or const ARR = ['a', 'b'];
inside a class or global scope (since PHP 7).
33. What’s the difference between function_exists()
and method_exists()
?
Answer:
function_exists()
checks for global functions, e.g., function_exists('strlen')
. method_exists()
checks for methods in a class or object, e.g., method_exists($obj, 'method')
.
34. How can you use namespaces in PHP?
Answer:
Declare with namespace MyApp;
at the file’s top. Access classes with \MyApp\ClassName
or use use MyApp\ClassName;
to import. Namespaces prevent naming conflicts.
35. What is the difference between $_COOKIE
and $_SESSION
?
Answer:
$_COOKIE
stores data client-side in the browser, accessible across sessions but less secure. $_SESSION
stores data server-side, tied to a session ID, and is more secure.
36. What’s the best way to hash a password in PHP?
Answer:
Use password_hash($password, PASSWORD_DEFAULT)
to securely hash passwords and password_verify($password, $hash)
to verify them, leveraging secure algorithms like bcrypt.
37. What are PSR standards in PHP?
Answer:
PSR (PHP Standard Recommendations) are coding standards by PHP-FIG to ensure interoperability and consistency, e.g., PSR-4 for autoloading, PSR-12 for coding style.
38. How can you automatically load classes?
Answer:
Use spl_autoload_register()
to define a custom autoloader or Composer’s autoloader via require 'vendor/autoload.php';
to load classes based on PSR-4 standards.
39. What’s the difference between json_encode()
and serialize()
?
Answer:
json_encode()
converts data to a JSON string, ideal for JavaScript or APIs. serialize()
creates a PHP-specific string, better for complex objects but not interoperable. Resources are converted to null
in both.
40. What is output buffering and how is it used?
Answer:
Output buffering captures output in memory before sending it to the client. Use ob_start()
to start, ob_get_clean()
to retrieve and clear, or ob_end_flush()
to send, e.g., for modifying output before display.
41. How do you handle time zones in PHP?
Answer:
Set the default time zone with date_default_timezone_set('UTC');
and use the DateTime
class with DateTimeZone
for precise time zone handling, e.g., $dt = new DateTime('now', new DateTimeZone('America/New_York'));
.
42. What’s the difference between throw
and trigger_error()
?
Answer:
throw
raises an Exception
object, caught by try...catch
. trigger_error()
generates a PHP error (e.g., E_USER_WARNING
) handled by error handlers, not exceptions.
43. What is a generator in PHP?
Answer:
A generator uses yield
to return values one at a time, conserving memory for large datasets, e.g., function gen() { for ($i = 0; $i < 10; $i++) { yield $i; } }
.
44. What is the difference between array_map()
and array_walk()
in PHP?
Answer:
array_map()
applies a callback to each element and returns a new array with the results, e.g., array_map('strtoupper', $arr)
. array_walk()
applies a callback to modify the original array in place and returns a boolean, e.g., array_walk($arr, function(&$v) { $v .= 'x'; });
.
45. What is the use of array_filter()
?
Answer:
array_filter()
filters array elements using a callback, keeping only those where the callback returns true
, e.g., array_filter($arr, function($v) { return $v > 0; });
.
46. What does $_SERVER['REQUEST_METHOD']
return?
Answer:
It returns the HTTP request method (e.g., GET
, POST
, PUT
, DELETE
) used to access the page.
47. What’s a common use case for late static binding?
Answer:
Late static binding allows static methods in a parent class to reference the called child class using static::
, useful in factories or static method inheritance, e.g., class Model { static function getClass() { return static::class; } }
.
48. How do you handle large file uploads in PHP?
Answer:
Adjust php.ini
settings (upload_max_filesize
, post_max_size
, memory_limit
) and use chunked uploads or stream processing to handle large files efficiently.
49. What does function &foo()
mean?
Answer:
It indicates the function returns a reference, allowing the caller to modify the returned variable directly, e.g., function &getVal() { static $val = 0; return $val; } $x = &getVal(); $x++;
.
50. What is Composer and why is it important?
Answer:
Composer is a dependency manager for PHP, handling package installation, autoloading, and version constraints. It simplifies project setup and ensures consistent library management, e.g., via composer.json
.

Hire Top LATAM Developers: Guide
We’ve prepared this guide that covers benefits, costs, recruitment, and remote team management to a succesful hiring of developers in LATAM.
Fill out the form to get our guide.
Advanced Level (3+ Years)
1. What is the difference between shallow and deep copy in the context of PHP objects?
Answer:
A shallow copy, created by clone
, duplicates an object’s properties but retains references to nested objects. A deep copy recursively clones all nested objects, often implemented in __clone()
. Example:
class Nested { public $value; }
class Test {
public $nested;
public function __clone() {
$this->nested = clone $this->nested; // Deep copy
}
}
2. Explain the difference between static
, self
, and parent
in class context.
Answer:
self
refers to the class where the method is defined. static
uses late static binding to reference the runtime class. parent
accesses the immediate parent class. Example:
class ParentClass { static function test() { echo self::class . ' vs ' . static::class; } }
class ChildClass extends ParentClass { }
ChildClass::test(); // Outputs: ParentClass vs ChildClass
3. How does PHP implement memory management and garbage collection?
Answer:
PHP uses reference counting to track variable references. A cycle-detection algorithm runs periodically to free memory from circular references, preventing leaks in long-running processes.
4. What are PHP Streams, and how are they used?
Answer:
Streams provide a unified interface for accessing data (files, network, memory) using functions like fopen()
, fread()
, and wrappers like php://stdin
. Contexts via stream_context_create()
customize behavior, e.g., HTTP headers.
5. How do Generators improve memory performance over regular functions?
Answer:
Generators use yield
to return values iteratively without storing the entire dataset in memory, ideal for large datasets. Example: function gen() { for ($i = 0; $i < 1000000; $i++) { yield $i; } }
.
6. What is the SPL in PHP?
Answer:
The Standard PHP Library (SPL) provides data structures (e.g., SplStack
, SplQueue
), iterators (e.g., ArrayIterator
), and exceptions (e.g., InvalidArgumentException
) for advanced programming tasks.
7. Explain how the Flyweight pattern can be implemented in PHP and its benefit.
Answer:
The Flyweight pattern shares immutable objects to reduce memory usage. Example: a factory caches and reuses objects with identical state:
class FlyweightFactory {
private static $instances = [];
public static function getInstance($state) {
return self::$instances[$state] ??= new Flyweight($state);
}
}
Benefits include reduced memory for repetitive objects, e.g., in text rendering.
8. What are some use cases for using closures bound with bindTo()
?
Answer:
bindTo()
changes a closure’s scope, useful for accessing private/protected members or dynamic method invocation. Example:
class Test { private $data = 'secret'; }
$closure = function() { return $this->data; };
echo $closure->bindTo(new Test, 'Test')(); // Outputs: secret
9. What are attributes (introduced in PHP 8) and how do they complement docblocks?
Answer:
Attributes provide structured metadata for classes, methods, or properties, parsed by the PHP engine. They complement docblocks (used for documentation) by enabling runtime validation. Example:
#[Route('/home')]
class HomeController { public function index() {} }
10. How would you implement middleware in native PHP?
Answer:
Implement a middleware stack where each callable processes a request and passes it to the next. Example:
class MiddlewareStack {
private $stack = [];
public function add(callable $middleware) { $this->stack[] = $middleware; }
public function handle($request) {
$next = fn($req) => $this->stack ? (array_shift($this->stack))($req, $next) : $req;
return $next($request);
}
}
11. Explain the differences between Composer’s require
and require-dev
.
Answer:
require
lists dependencies needed for production. require-dev
lists dependencies for development or testing (e.g., PHPUnit), excluded in production installs.
12. What is dependency injection and how is it implemented in PHP?
Answer:
Dependency injection passes dependencies to a class, typically via constructor or setters, for loose coupling. Example:
class UserService {
private $db;
public function __construct(Database $db) { $this->db = $db; }
}
13. How do you handle circular dependencies in PHP projects?
Answer:
Refactor using interfaces, dependency inversion, or service locators to break cycles. Alternatively, split into distinct services or use lazy loading in DI containers.
14. What is opcode caching and how does it affect PHP performance?
Answer:
Opcode caching (e.g., OPcache) stores compiled PHP bytecode in memory, reducing parsing and compilation overhead, significantly improving performance for repeated script executions.
15. How does PHP handle multithreading or concurrency?
Answer:
PHP is single-threaded but supports concurrency via the parallel
extension (PHP 7.4+) or multi-processing (e.g., pcntl_fork
). Asynchronous tasks can use queues or ReactPHP.
16. What is the output of echo (object) "10";
?
Answer:
Casting "10"
to an object creates a stdClass
with a scalar
property set to 10
. However, echo (object) "10"
throws an error unless __toString()
is defined. Example:
$obj = (object) "10";
var_dump($obj); // object(stdClass)#1 (1) { ["scalar"]=> string(2) "10" }
17. How does the Just-In-Time (JIT) compiler in PHP 8 improve performance, and what are its limitations?
Answer:
JIT compiles PHP bytecode to machine code at runtime, optimizing CPU-intensive tasks (e.g., mathematical computations). Limitations include minimal benefits for I/O-bound web apps and increased memory usage. Enable via opcache.jit_buffer_size
.
18. Describe how autoloading works with PSR-4 and Composer.
Answer:
PSR-4 maps namespaces to directories. Composer generates a class map or scans directories to load classes automatically, e.g., "App\\": "src/"
in composer.json
maps App\ClassName
to src/ClassName.php
.
19. What’s the difference between Throwable
, Exception
, and Error
in PHP?
Answer:
Throwable
is the base interface for Exception
(user or runtime errors, e.g., InvalidArgumentException
) and Error
(engine-level issues, e.g., TypeError
). Both can be caught in try...catch
.
20. How would you implement caching in a high-load PHP application?
Answer:
Use in-memory stores (Redis, Memcached) for dynamic data, filesystem caches for static content, and HTTP headers (e.g., ETag
, Cache-Control
). Abstract with a caching layer, e.g., Symfony Cache.
21. What are weak references in PHP and when would you use them?
Answer:
Weak references (WeakReference
in PHP 7.4+) reference objects without preventing garbage collection, useful in caching to avoid memory leaks. Example: $ref = WeakReference::create($obj);
.
22. What are value objects and how do they differ from entities?
Answer:
Value objects are immutable, compared by value (e.g., a Money object with amount and currency). Entities have a unique ID and mutable state, used in domain-driven design.
23. What is the difference between a Service and a Repository in DDD?
Answer:
A Repository manages persistence, acting like a collection of entities (e.g., UserRepository
). A Service encapsulates domain logic not tied to a specific entity or value object.
24. How can you detect memory leaks in a long-running PHP process?
Answer:
Use tools like Xdebug, memory_get_usage()
, or Blackfire to monitor memory. Analyze logs for increasing memory usage, often due to circular references or large caches.
25. What is reflection in PHP and how is it used?
Answer:
Reflection inspects classes, methods, or properties at runtime via classes like ReflectionClass
. It’s used for dynamic invocation or metadata parsing, e.g., reading attributes in frameworks.
26. How do you implement a custom session handler?
Answer:
Implement SessionHandlerInterface
with methods like open
, read
, write
, and register with session_set_save_handler(new CustomHandler)
, e.g., for Redis-based sessions.
27. What are the risks of deserializing untrusted data in PHP?
Answer:
Untrusted data can trigger __wakeup()
or __destruct()
, leading to arbitrary code execution or injection. Use allowed_classes
in unserialize()
to restrict classes.
28. How would you structure a plugin system in PHP?
Answer:
Use interfaces for plugins and an event dispatcher for hooks. Load plugins dynamically via reflection or a DI container, e.g., WordPress-style action filters.
29. What are PHP’s union types and intersection types, and how are they used?
Answer:
Union types (PHP 8+) allow multiple types (e.g., function test(string|int $param)
). Intersection types (PHP 8.1+) require all types (e.g., function test(Countable&Traversable $param)
). Example:
function process(string|int $input): string|bool {
return is_string($input) ? $input : false;
}
30. What are the limitations of PHP’s type system?
Answer:
PHP’s gradual typing lacks generics, has limited union type support pre-PHP 8, and type hints are runtime-enforced, not compile-time, which can miss errors until execution.
31. How do you write a high-performance REST API in PHP?
Answer:
Use a micro-framework (Slim, Lumen), enable OPcache, cache responses (Redis), paginate queries, optimize middleware, and offload tasks to queues (e.g., Laravel Queue).
32. How do you validate nested data structures in PHP?
Answer:
Use recursive validation with libraries like Symfony Validator or Respect/Validation, defining rules via metadata or attributes for nested arrays/objects.
33. What is the purpose of a Dependency Injection Container?
Answer:
A DI container (e.g., PHP-DI) automates object creation and dependency resolution, improving testability and decoupling. Example: $container->get('UserService');
.
34. What are the dangers of relying on eval()
?
Answer:
eval()
executes arbitrary code, risking security vulnerabilities (e.g., code injection), performance issues, and maintainability problems. Avoid it in favor of safer alternatives.
35. What’s the difference between lazy and eager loading in Doctrine ORM?
Answer:
Lazy loading fetches related data only when accessed, reducing initial query load. Eager loading retrieves related data upfront using JOIN
s, minimizing subsequent queries.
36. How do you handle database versioning in PHP projects?
Answer:
Use migration tools (Phinx, Doctrine Migrations) to version-control schema changes, applying incremental updates via scripts, e.g., php vendor/bin/phinx migrate
.
37. How would you implement an event-driven architecture in PHP?
Answer:
Use an event dispatcher (e.g., Symfony EventDispatcher) with events and listeners. Example: $dispatcher->dispatch(new UserRegistered($user));
triggers listeners for email or logging tasks.
38. How does PHP handle session locking?
Answer:
PHP locks the session file during a request, blocking concurrent requests until session_write_close()
is called, ensuring data consistency but potentially causing delays.
39. What is a monorepo and how would you structure one in PHP?
Answer:
A monorepo stores multiple projects in one repository. Structure with Composer path repositories, distinct namespaces, and build tools like Robo for deployment.
40. What is the output of json_decode('{"a":1}', true)['b'] ?? 'default';
?
Answer:
The output is default
. The array key 'b'
doesn’t exist, so the null coalescing operator (??
) returns 'default'
.
41. How does a PHP extension work?
Answer:
PHP extensions are C libraries compiled into the PHP engine, adding functions, classes, or modifying internals via hooks, e.g., ext/pdo
for database access.
42. How would you mock a final class or private method in PHP unit tests?
Answer:
Use wrappers or Mockery with reflection to test private methods indirectly. For final classes, use interfaces or proxy objects to isolate testable logic.
43. What is the purpose of __sleep()
and __wakeup()
?
Answer:
__sleep()
filters properties before serialization, e.g., excluding transient data. __wakeup()
reinitializes objects after unserialization, e.g., reconnecting to a database.
44. What is the benefit of immutable objects in PHP?
Answer:
Immutable objects prevent unintended changes, simplify state management, enhance thread-safety, and suit value objects or caching. Example: a Money
class with fixed amount and currency.
45. How do you track down a memory leak in a Laravel or Symfony application?
Answer:
Use Blackfire, Xdebug, or memory_get_usage()
to profile memory. Check for circular references, large caches, or unclosed resources in service containers or event listeners.
46. How does PHP internals parse and execute code?
Answer:
PHP tokenizes code, builds an AST, compiles to opcodes, and executes via the Zend VM. OPcache stores opcodes to skip parsing/compilation, improving performance.
47. What’s the difference between Symfony Events and Laravel Events?
Answer:
Symfony uses a dispatcher with listeners/subscribers for flexible event handling. Laravel supports queued or broadcast events, enabling sync/async processing via queues or WebSockets.
48. What is the PHP-FPM slow log and how is it used?
Answer:
PHP-FPM’s slow log tracks requests exceeding request_slowlog_timeout
. Enable in php-fpm.conf
to log stack traces for performance debugging.
49. What’s the role of middleware in a PSR-15 application?
Answer:
PSR-15 middleware processes requests and responses in a stack, handling cross-cutting concerns like authentication or logging. Each middleware calls the next or short-circuits.
50. What are variadic functions in PHP and how do they work?
Answer:
Variadic functions use ...
to accept variable arguments as an array. Example: function sum(...$nums) { return array_sum($nums); }
allows sum(1, 2, 3)
.