🐘

PHP MCQ

Test your PHP knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 40 Beginner 40 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

What does PHP stand for?

B

Correct Answer

PHP: Hypertext Preprocessor

Explanation

PHP is a recursive acronym: PHP: Hypertext Preprocessor. It is a server-side scripting language.

2

How do you start a PHP block of code?

B

Correct Answer

<?php

Explanation

<?php is the standard opening tag. The short tag <? requires short_open_tag=On and is not recommended for portability.

3

How do you declare a variable in PHP?

C

Correct Answer

$name = "John"

Explanation

PHP variables start with a $ sign followed by the name. PHP is dynamically typed — no type declaration is needed.

4

Which function outputs text in PHP?

D

Correct Answer

echo

Explanation

echo and print both output text. echo can output multiple comma-separated strings; print returns 1 (a value).

5

How do you write a single-line comment in PHP?

B

Correct Answer

// comment or # comment

Explanation

PHP supports // and # for single-line comments and /* ... */ for multi-line comments.

6

What is the concatenation operator in PHP?

C

Correct Answer

.

Explanation

The dot (.) operator concatenates strings in PHP. $str = "Hello" . " World";

7

How do you create an array in PHP?

A

Correct Answer

$arr = array(1, 2, 3) or $arr = [1, 2, 3]

Explanation

PHP supports both array() constructor and the shorthand [] syntax (PHP 5.4+).

8

What does isset() do?

B

Correct Answer

Checks if a variable is set and is not null

Explanation

isset($var) returns true if $var is declared and not null. It returns false for null values and undefined variables.

9

What is the difference between == and === in PHP?

B

Correct Answer

== checks value equality with type juggling; === checks value and type equality

Explanation

0 == "0" is true (type juggling). 0 === "0" is false (different types: int vs string).

10

How do you define a function in PHP?

C

Correct Answer

function greet() {}

Explanation

PHP functions are declared with the function keyword followed by the function name and parentheses.

11

What does the count() function do?

B

Correct Answer

Returns the number of elements in an array

Explanation

count($array) returns the number of elements. strlen() returns string length.

12

Which PHP superglobal contains form data sent via POST?

C

Correct Answer

$_POST

Explanation

$_POST contains data submitted via HTTP POST. $_GET contains URL query parameters. $_REQUEST contains both.

13

What is a PHP class?

B

Correct Answer

A blueprint for creating objects with properties and methods

Explanation

PHP classes are defined with class MyClass { } and instantiated with new MyClass().

14

What does $this refer to inside a PHP class method?

C

Correct Answer

The current object instance

Explanation

$this refers to the current object instance inside non-static class methods.

15

How do you inherit from a class in PHP?

B

Correct Answer

class Dog extends Animal

Explanation

PHP uses extends for class inheritance and implements for interfaces.

16

What is the purpose of the __construct() method?

B

Correct Answer

It is the constructor, automatically called when an object is created

Explanation

__construct() initializes object properties when new MyClass() is called.

17

What does the include statement do?

B

Correct Answer

Includes a file and continues on failure with a warning

Explanation

include gives a warning but continues if the file is not found. require gives a fatal error and halts. include_once and require_once prevent multiple inclusions.

18

What is the output of var_dump(true)?

C

Correct Answer

bool(true)

Explanation

var_dump() outputs the type and value. For true: bool(true). It's more informative than echo or print_r.

19

How do you access a value from an associative array?

C

Correct Answer

$arr['key']

Explanation

Associative array values are accessed with $arr['key'] or $arr["key"].

20

What does PHP's null coalescing operator ?? do?

B

Correct Answer

Returns the left operand if it exists and is not null; otherwise returns the right operand

Explanation

$name = $_GET['name'] ?? 'Anonymous' returns $_GET['name'] if set, otherwise 'Anonymous'. Added in PHP 7.

21

What is the difference between array_push() and $arr[] = ?

B

Correct Answer

They are functionally equivalent; $arr[] is slightly faster as it avoids function call overhead

Explanation

Both append to the end of an array. $arr[] = $val is preferred for single elements; array_push($arr, $a, $b) for multiple at once.

22

What is a PHP interface?

B

Correct Answer

A contract specifying method signatures that implementing classes must define

Explanation

Interfaces declare method signatures without implementations. A class implements an interface with the implements keyword.

23

What is the scope of a variable defined inside a PHP function?

B

Correct Answer

Local — accessible only within that function

Explanation

PHP functions have their own scope. To access a global variable inside a function, use the global keyword or $GLOBALS superglobal.

24

How do you convert a string to an integer in PHP?

A

Correct Answer

intval($str) or (int)$str

Explanation

intval("42") or (int)"42" both return 42. intval() allows specifying a base (e.g., intval("0xFF", 16)).

25

What does empty() check in PHP?

B

Correct Answer

If a variable is considered empty: "", 0, "0", null, false, [], or unset

Explanation

empty($var) returns true for "", 0, "0", null, false, [], 0.0. It suppresses errors for undefined variables.

26

What is the purpose of PHP sessions?

B

Correct Answer

To store user-specific data on the server across multiple requests

Explanation

Sessions store data server-side across requests. Start with session_start() and store data in $_SESSION. A session ID is stored in a cookie.

27

How do you call a static method in PHP?

C

Correct Answer

MyClass::method()

Explanation

The :: (Paamayim Nekudotayim) operator calls static methods: MyClass::method(). static:: is for late static binding.

28

What does the foreach loop do in PHP?

B

Correct Answer

Iterates over each key-value pair of an array

Explanation

foreach ($array as $key => $value) iterates over arrays and objects. foreach ($array as $value) skips the key.

29

What is the PHP spaceship operator <=>?

B

Correct Answer

Returns -1, 0, or 1 for less-than, equal, or greater-than comparisons

Explanation

$a <=> $b returns -1 if $a < $b, 0 if equal, 1 if $a > $b. Added in PHP 7, useful for usort() callbacks.

30

What does htmlspecialchars() do?

B

Correct Answer

Converts special characters to HTML entities to prevent XSS

Explanation

htmlspecialchars() converts <, >, &, ", ' to HTML entities, preventing cross-site scripting (XSS) attacks.

31

What does the ternary operator look like in PHP?

B

Correct Answer

$condition ? $x : $y

Explanation

The ternary operator $result = $condition ? "yes" : "no" evaluates to $x if true, $y if false.

32

What is a PHP trait?

B

Correct Answer

A mechanism for reusing method sets in single-inheritance languages

Explanation

Traits allow horizontal code reuse without inheritance. use MyTrait; inside a class includes the trait's methods.

33

What does unset() do?

B

Correct Answer

Destroys a variable, removing it from scope

Explanation

unset($var) destroys the variable. Inside a function, it only affects the local variable unless passed by reference.

34

Which function sorts an array in ascending order?

C

Correct Answer

sort($arr)

Explanation

sort() sorts by value and re-indexes keys. asort() preserves keys. ksort() sorts by key. rsort() sorts in descending order.

35

What is PHP's PDO?

C

Correct Answer

PHP Data Objects — a database abstraction layer

Explanation

PDO provides a consistent interface for accessing multiple databases (MySQL, PostgreSQL, SQLite, etc.) and supports prepared statements.

36

What does the print_r() function do?

B

Correct Answer

Prints human-readable information about a variable, including array contents

Explanation

print_r() displays arrays and objects in a readable format. Pass true as the second argument to return the output as a string instead of printing it.

37

What is PHP type juggling?

B

Correct Answer

PHP's automatic conversion of types in comparisons and operations

Explanation

PHP automatically converts types in loose comparisons. "1" == 1 is true because PHP juggles "1" to integer 1. Use === to avoid this.

38

What does declare(strict_types=1) do?

B

Correct Answer

Forces strict type checking for scalar type declarations in that file

Explanation

With strict_types=1 at the top of a file, passing a string to a function expecting int throws a TypeError instead of coercing.

39

What are PHP magic methods?

B

Correct Answer

Special double-underscore methods automatically called by PHP in certain situations

Explanation

Magic methods like __construct, __get, __set, __toString, __invoke are called automatically by PHP in specific contexts.

40

What does str_replace() do?

B

Correct Answer

Finds and replaces occurrences of a substring in a string

Explanation

str_replace("cat", "dog", "the cat sat") returns "the dog sat". It is case-sensitive; str_ireplace() is case-insensitive.

1

What is the difference between abstract class and interface in PHP?

B

Correct Answer

Abstract classes can have implemented methods and properties; interfaces only declare method signatures (PHP 8 allows constants)

Explanation

Abstract classes can provide partial implementations and state. A class can only extend one abstract class but implement multiple interfaces.

2

What is a PHP closure?

B

Correct Answer

An anonymous function that can capture variables from the surrounding scope using use

Explanation

$fn = function($x) use ($factor) { return $x * $factor; }; captures $factor by value. use (&$var) captures by reference.

3

What is PHP's late static binding?

B

Correct Answer

static:: refers to the class on which a static method was actually called, not the class where it was defined

Explanation

self:: refers to the defining class. static:: refers to the called class (late binding), enabling proper polymorphism in static methods.

4

What is dependency injection in PHP?

B

Correct Answer

Providing a class's dependencies from outside rather than having the class create them, improving testability

Explanation

DI passes dependencies (e.g., a database connection) via constructors or methods instead of using new inside the class, enabling mocking in tests.

5

What is a PHP generator?

B

Correct Answer

A function using yield to produce values lazily, useful for large datasets

Explanation

function gen() { yield 1; yield 2; } creates a Generator object. Values are produced on-demand, saving memory for large sequences.

6

What does PHP's array_map() do?

B

Correct Answer

Applies a callback to each element and returns a new array of results

Explanation

array_map(fn($x) => $x * 2, [1,2,3]) returns [2,4,6]. For filtering use array_filter(); for reducing use array_reduce().

7

What are named arguments in PHP 8?

B

Correct Answer

Passing arguments by parameter name, allowing any order and skipping optional parameters

Explanation

array_slice(array: $arr, offset: 0, length: 3) uses named args. They improve readability and allow skipping middle optional parameters.

8

What is the match expression in PHP 8?

B

Correct Answer

A strict-comparison expression that returns a value, replacing switch with no type juggling or fall-through

Explanation

match($val) { 1 => "one", 2 => "two" } uses === comparison, throws UnhandledMatchError for no match, and has no fall-through.

9

What is PHP's Fibers feature (PHP 8.1)?

B

Correct Answer

Lightweight coroutines with explicit suspension and resumption primitives

Explanation

Fibers allow suspending and resuming execution at any point, enabling cooperative multitasking and async-like patterns without callback hell.

10

What is PHP's union type declaration?

B

Correct Answer

A type declaration accepting multiple types: function f(int|string $x)

Explanation

PHP 8 union types (int|string) allow parameters or returns to be one of the listed types. PHP 8.2 adds intersection types (Iterator&Countable).

11

What are PHP attributes (PHP 8)?

B

Correct Answer

Structured metadata annotations on classes, functions, and parameters using #[Attribute]

Explanation

#[Route("/home")] is an attribute. Unlike docblock annotations, attributes are native PHP syntax readable via Reflection, enabling frameworks to use them natively.

12

What does PHP's null safe operator ?-> do?

B

Correct Answer

Chains method calls safely, returning null if any part of the chain is null instead of throwing an error

Explanation

$user?->getAddress()?->getCity() returns null if $user or getAddress() is null, avoiding multiple isset() checks. Added in PHP 8.

13

What is the difference between include_once and require_once?

B

Correct Answer

Both include a file at most once; include_once issues a warning on failure, require_once causes a fatal error

Explanation

The _once variants track included files to prevent duplicate inclusion. The difference between include and require is error behavior.

14

What is a PSR in PHP?

B

Correct Answer

PHP Standards Recommendation — interoperability guidelines from PHP-FIG

Explanation

PSR (PHP Standards Recommendation) guidelines include PSR-4 (autoloading), PSR-7 (HTTP messages), and PSR-12 (coding style).

15

What is PSR-4 autoloading?

B

Correct Answer

A standard mapping namespace prefixes to directory paths, enabling automatic class loading without manual require statements

Explanation

PSR-4 maps App\ to src/. Composer's autoloader implements it; class App\Controllers\HomeController maps to src/Controllers/HomeController.php.

16

What is PHP's match expression's advantage over switch?

B

Correct Answer

match uses strict (===) comparison, has no fall-through, must be exhaustive or throw, and is an expression returning a value

Explanation

switch uses loose == comparison and allows accidental fall-through. match uses ===, must handle all cases (or have default), and can be assigned directly.

17

What is a PHP readonly property (PHP 8.1)?

B

Correct Answer

A property that can only be initialized once; subsequent writes throw an error

Explanation

public readonly string $name allows setting $name once (usually in __construct). Any subsequent write throws Error.

18

What does PHP's splat operator ... do?

A

Correct Answer

Spreads an array as individual function arguments or collects variadic parameters

Explanation

function f(...$args) collects variadic args. f(...$array) unpacks the array as individual arguments.

19

What is the difference between array_merge() and array + array?

B

Correct Answer

array_merge renumbers numeric keys and overwrites string keys; + keeps the first array's values for duplicate keys

Explanation

[1,2] + [3,4,5] = [1,2,5] (+ keeps first values for existing keys). array_merge([1,2],[3,4,5]) = [1,2,3,4,5] (appends).

20

What is PHP's object cloning?

B

Correct Answer

Creating a shallow copy of an object with clone, triggering __clone() if defined

Explanation

$copy = clone $original; creates a shallow copy. Define __clone() to perform deep copies of nested objects.

21

What is a PHP enumeration (Enum) added in PHP 8.1?

B

Correct Answer

A special type with a fixed set of named values, optionally backed by string or int

Explanation

enum Status { case Active; case Inactive; } Pure enums have no value. Backed enums: enum Status: string { case Active = 'active'; }.

22

What is PHP's SPL (Standard PHP Library)?

B

Correct Answer

A collection of interfaces, classes, and functions for data structures, iterators, and file handling

Explanation

SPL provides SplStack, SplQueue, SplDoublyLinkedList, ArrayObject, RecursiveIteratorIterator, and more.

23

What is PHP's type coercion in strict mode?

B

Correct Answer

In strict mode (strict_types=1), passing a wrong type throws TypeError with no coercion

Explanation

Without strict_types, PHP coerces "5" to 5 when an int is expected. With strict_types=1, this throws a TypeError.

24

What is the purpose of PHP's Composer?

B

Correct Answer

A dependency manager for PHP that handles package installation and autoloading

Explanation

Composer manages project dependencies via composer.json, installs packages into vendor/, and generates the PSR-4 autoloader.

25

What is PHP's arrow function (fn)?

B

Correct Answer

A concise closure syntax that implicitly captures outer variables by value

Explanation

fn($x) => $x * $factor automatically captures $factor by value without use. Added in PHP 7.4.

26

What does PHP's intl extension provide?

B

Correct Answer

Internationalization functions for locale-aware formatting, collation, and message parsing

Explanation

The intl extension wraps ICU library functionality: NumberFormatter, DateFormatter, Collator, MessageFormatter for locale-sensitive operations.

27

What is PHP's Reflection API used for?

B

Correct Answer

Inspecting classes, interfaces, functions, and methods at runtime to get metadata

Explanation

ReflectionClass, ReflectionMethod, ReflectionProperty allow inspecting code structure at runtime — used by DI containers, ORMs, and testing frameworks.

28

What is PHP's session fixation vulnerability?

B

Correct Answer

When an attacker forces a known session ID on a user, then authenticates as them after login

Explanation

Fix session fixation by calling session_regenerate_id(true) after login to assign a new session ID, invalidating any pre-login ID set by an attacker.

29

What is PHP's Inversion of Control (IoC) container?

B

Correct Answer

A component that automatically resolves and injects class dependencies based on type hints, used by Laravel's Service Container

Explanation

IoC containers auto-wire dependencies by inspecting constructor type hints via Reflection. Laravel's App::make() and type-hint injection in controllers use this.

30

What is the difference between PHP's header() and setcookie()?

B

Correct Answer

header() sends any HTTP header; setcookie() is a convenience wrapper for Set-Cookie headers. Both must be called before any output

Explanation

setcookie("name", "value", time()+3600) is equivalent to header("Set-Cookie: name=value; ..."). Both require no output before they are called.

31

What is PHP's array_walk() function?

B

Correct Answer

Applies a callback to each element of an array by reference, modifying the array in place

Explanation

array_walk($arr, function(&$val, $key) { $val = strtoupper($val); }) modifies values in place. Return value is bool, not the modified array.

32

What does PHP's compact() do?

B

Correct Answer

Creates an associative array from variable names and their values

Explanation

$name = "Alice"; $age = 30; compact("name", "age") returns ["name" => "Alice", "age" => 30]. The inverse is extract().

33

What is the purpose of PHP's final keyword on methods?

B

Correct Answer

Prevents child classes from overriding the method

Explanation

final public function calculate() in a parent class prevents child classes from overriding it, enforcing the algorithm's behavior.

34

What is PHP's abstract static method debate?

B

Correct Answer

PHP generates a strict standards warning for abstract static methods because static methods cannot be polymorphic in the traditional sense

Explanation

PHP 5.3+ generates a strict warning: abstract static methods are logically problematic since static methods cannot be truly overridden (no dynamic dispatch).

35

What is PHP's output buffering?

B

Correct Answer

ob_start() captures all output to a buffer, allowing modification or capture before sending to the client

Explanation

ob_start(); echo "Hello"; $content = ob_get_clean(); captures "Hello" without sending it. Used for template engines and testing.

36

What is PHP's DateTimeImmutable class?

B

Correct Answer

An immutable DateTime class where modification methods return new instances instead of modifying in place

Explanation

Unlike DateTime::modify() which mutates, DateTimeImmutable::modify() returns a new object. Prevents accidental mutation in code that passes dates around.

37

What is PHP's splat in array unpacking?

B

Correct Answer

Using ... to unpack an array into positional values: [$first, ...$rest] = $array or [...$a, ...$b]

Explanation

PHP 8.1 allows array unpacking with string keys: [...$defaults, ...$overrides]. The splat creates a merged array with later values overwriting earlier ones.

38

What is PHP's first class callable syntax (PHP 8.1)?

B

Correct Answer

Closure::fromCallable($fn) as a shorthand: $fn = strlen(...) creates a closure from a function

Explanation

$fn = strlen(...) is equivalent to Closure::fromCallable("strlen"). Works for functions, methods, static methods: $fn = $obj->method(...).

39

What is PHP's fibers vs generators distinction?

B

Correct Answer

Generators use yield and can only suspend at yield points; Fibers can suspend anywhere in the call stack using Fiber::suspend()

Explanation

Generators are limited to yielding at explicit yield statements. Fibers can suspend at any point in nested function calls, enabling deeper coroutine patterns.

40

What is the PHP serialize() vs json_encode() for data persistence?

B

Correct Answer

serialize() is PHP-specific and handles objects with __sleep/__wakeup; json_encode() produces portable JSON but loses object class info

Explanation

serialize() preserves PHP objects (class name + state) for PHP-to-PHP transfer. json_encode() is portable, human-readable, but loses PHP class information.

1

What is PHP's OPcache and how does it improve performance?

B

Correct Answer

An opcode cache that stores precompiled script bytecode in memory, eliminating repeated parsing and compilation

Explanation

OPcache stores compiled PHP bytecode in shared memory. Subsequent requests skip parsing/compilation, dramatically reducing response time.

2

What is the PHP Fibers API and how does it differ from async/await?

B

Correct Answer

Fibers provide low-level stackful coroutines; async/await is syntactic sugar built on top by frameworks using the event loop

Explanation

PHP Fibers (8.1) are stackful coroutines with Fiber::suspend(). Async frameworks like ReactPHP use Fibers as the foundation for async/await syntax.

3

What is PHP's Just-In-Time (JIT) compiler introduced in PHP 8?

B

Correct Answer

A component built on OPcache that compiles hot bytecode paths to native machine code during execution

Explanation

PHP 8's JIT (tracing and function modes) compiles frequently executed code to native x86 machine code, improving CPU-intensive workloads.

4

How does PHP handle object references vs value copies?

B

Correct Answer

Objects are assigned by handle (reference to the object store), so assignment copies the handle not the object; use clone for a copy

Explanation

PHP objects are passed by handle. $b = $a means both point to the same object. Modifying $b modifies the same object. Use clone $a for an independent copy.

5

What is PHP's weak map (WeakMap in PHP 8)?

B

Correct Answer

A map keyed by objects where entries are garbage collected when the key object has no other references

Explanation

WeakMap allows attaching data to objects without preventing their garbage collection. Useful for caching per-object metadata without memory leaks.

6

What are PHP intersection types (PHP 8.1)?

B

Correct Answer

A type declaration requiring a value to satisfy multiple type constraints simultaneously: Iterator&Countable

Explanation

function f(Iterator&Countable $x) requires $x to implement both Iterator and Countable. Intersection types are the dual of union types.

7

What is PHP's copy-on-write mechanism for arrays?

B

Correct Answer

Arrays share a single zval structure until one is modified, at which point PHP copies the array (lazy duplication)

Explanation

$b = $a copies the reference count. When $b is modified, PHP separates them (copy-on-write). This avoids expensive copies when arrays are only read.

8

What is PHP's zval structure?

A

Correct Answer

The internal representation of a PHP value in the Zend engine, storing type, value, and reference count

Explanation

A zval (Zend value) is the C structure holding any PHP value: type flag, reference count, and a union for the value. PHP 7 redesigned zvals to reduce memory usage.

9

What is PHP's named arguments interaction with function signature changes?

B

Correct Answer

Renaming a parameter in a library function breaks callers using named arguments for that parameter — a BC-breaking change

Explanation

Named arguments bind by parameter name, so renaming a parameter is a breaking change for any callers relying on the old name.

10

What is a Psalm or PHPStan and how do they differ from PHP's runtime type checks?

B

Correct Answer

Static analysis tools that find type errors, dead code, and logic bugs at analysis time without executing the code

Explanation

Psalm and PHPStan analyze PHP code statically, catching type mismatches and null pointer bugs that PHP's runtime would only catch when that code path is executed.

11

What is PHP's memory_limit and how does it interact with memory-heavy operations?

B

Correct Answer

memory_limit in php.ini caps peak memory usage; large array operations or image processing can hit it, causing fatal errors

Explanation

Use ini_set("memory_limit", "512M") for scripts requiring more memory. Generators and lazy iterators avoid loading entire datasets into memory.

12

How does PHP's session save handler work and how can it be customized?

B

Correct Answer

Implementing SessionHandlerInterface and passing it to session_set_save_handler() allows storing sessions in Redis, databases, or custom backends

Explanation

Custom session handlers implement open, close, read, write, destroy, gc methods. Used for distributed session storage in horizontally-scaled PHP applications.

13

What are PHP SPL data structures and their advantages over arrays?

B

Correct Answer

SplStack, SplQueue, SplHeap, SplDoublyLinkedList provide semantically correct types with O-optimal operations vs PHP arrays used as all-purpose structures

Explanation

Using SplStack enforces LIFO semantics. SplMinHeap gives O(log n) min-element access. They communicate intent and enforce correctness over generic arrays.

14

What is PHP's preloading feature (PHP 7.4+)?

B

Correct Answer

opcache.preload compiles specified PHP files once at FPM start, storing compiled bytecode in shared memory for all worker processes

Explanation

With preloading, frameworks precompile their core files. Workers inherit the preloaded code without parsing overhead. Requires FPM restart to update preloaded files.

15

What is PHP's named arguments interaction with variadic functions?

B

Correct Answer

Named arguments must come before variadic arguments, and variadic parameters cannot receive named arguments individually

Explanation

function f(string $name, ...$args): named args like name: "x" work, but variadic ...$args cannot be individually targeted by name.

16

What is PHP's match expression behavior with no matching arm?

B

Correct Answer

Throws UnhandledMatchError, unlike switch which falls through to the end silently

Explanation

match($val) without a default that covers all cases throws UnhandledMatchError when no arm matches. This is intentional — use default to handle unexpected values explicitly.

17

What is PHP's "never" return type?

B

Correct Answer

A return type for functions that never return normally — they always throw or call exit()

Explanation

function redirect(string $url): never { header("Location: $url"); exit(); } — never communicates to static analyzers and the reader that this function never returns.

18

What is a PHP decorator pattern using __call?

B

Correct Answer

Implementing __call to intercept unknown method calls and delegate to a wrapped object, adding behavior transparently

Explanation

class Logger { function __call($name, $args) { log($name); return $this->wrapped->$name(...$args); } } wraps any object adding logging without modifying it.

19

What is the behavior of PHP's loose comparison with "0" and false?

B

Correct Answer

"0" == false is true because PHP converts "0" to 0 then to false; but "0" is truthy in boolean context

Explanation

PHP type juggling: "0" is falsy (empty-string-like in bool context), so "0" == false is true. But (bool)"0" === false. This asymmetry is a known PHP gotcha, fixed with ===.

20

What is PHP's static analysis type system compared to TypeScript?

B

Correct Answer

PHP's type system is opt-in with nullable types and union types; tools like PHPStan add generics, conditional types, and template annotations via docblocks

Explanation

PHP's runtime types are enforced by declare(strict_types=1) and type declarations. Generic types (Collection<User>) are only in docblocks, analyzed by Psalm/PHPStan, not enforced at runtime.