How to Pass a PHP Interview: Top Questions and Answers

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Pass a PHP Interview: Breakdown of Top Questions



A PHP developer interview is not just a test of syntax, but also a test of understanding architecture, security, and modern standards (PSR). In this article, we have collected 10 key questions that are most often asked in interviews for Junior and Middle levels. Each question is accompanied by an explanation, a code example, and typical pitfalls.



1. What is the difference between echo and print? And print_r vs var_dump?

This is a basic question that tests knowledge of built-in output functions.

  • echo — a language construct, does not return a value. Works faster than print.
  • print — also a construct, but always returns 1. Can be used in expressions.
  • print_r — outputs human-readable information about a variable (arrays, objects). Returns a string if the second parameter is true.
  • var_dump — outputs the type and value of a variable, including the string length. Useful for debugging.
<?php$arr = ['a' => 1, 'b' => 2];echo print_r($arr, true); // Returns a string, does not output immediatelyvar_dump($arr);           // array(2) { ["a"]=> int(1) ["b"]=> int(2) }?>


2. What is class autoloading and how does it work with Composer?

Autoloading allows PHP to automatically load classes when they are first accessed, without an explicit require_once.

  • Previously, the spl_autoload_register() function was used.
  • Now the de facto standard is Composer and its autoloader.
  • Composer supports PSR-4 (namespaces) and PSR-0 (deprecated).
// composer.json{    "autoload": {        "psr-4": {            "App\\\\": "src/"        }    }}

// After composer dump-autoload// File src/User.php with namespace App;$user = new \\App\\User(); // Will be loaded automatically


3. Difference between include, require, include_once and require_once

A question on understanding working with external files and error handling.

  • include — issues a Warning if the file is not found, the script continues execution.
  • require — issues a Fatal Error, the script stops.
  • *_once — checks if the file has already been included before and does not include it again.

Pitfall: Using include in a loop can cause repeated inclusion and a function redefinition error if include_once is not used.



4. How does PDO work and why is it better than mysql_* functions?

PDO (PHP Data Objects) is an interface for working with databases. It is mandatory knowledge for any modern PHP developer.

  • Supports different DBMS (MySQL, PostgreSQL, SQLite) — just change the DSN.
  • Uses prepared statements, which protects against SQL injections.
  • Convenient work with transactions and error handling via exceptions.
<?php$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';$pdo = new PDO($dsn, 'user', 'pass', [    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');$stmt->execute(['email' => $email]);$user = $stmt->fetch(PDO::FETCH_ASSOC);?>


5. What are magic methods in PHP? Provide examples

Magic methods start with a double underscore (__) and are called automatically during certain actions with an object.

  • __construct() — called when an object is created.
  • __get() / __set() — called when accessing inaccessible or undefined properties.
  • __call() / __callStatic() — called when calling inaccessible methods.
  • __toString() — allows a class to decide how to react when treated as a string.
  • __invoke() — called when an object is used as a function.
<?phpclass User {    private $data = [];

public function __get($name) { return $this->data[$name] ?? null; }

public function __set($name, $value) { $this->data[$name] = $value; }

public function __toString() { return $this->data['name'] ?? 'Guest'; }}

$user = new User();$user->name = 'Alice';echo $user->name; // Aliceecho $user; // Alice?>


6. What are the differences between self, static, and parent?

This question tests understanding of late static binding and inheritance.

  • self — always refers to the class where it is written. Does not support polymorphism.
  • static — refers to the class that is called at runtime (late static binding).
  • parent — refers to the parent class.
<?phpclass ParentClass {    protected static $name = 'Parent';

public static function getName() { return self::$name; // Always 'Parent' }

public static function getNameStatic() { return static::$name; // Depends on the calling class }}

class ChildClass extends ParentClass { protected static $name = 'Child';}

echo ChildClass::getName(); // Parentecho ChildClass::getNameStatic(); // Child?>


7. What is Dependency Injection and why is it used?

Dependency Injection (DI) is a design pattern where an object receives its dependencies from the outside, rather than creating them itself.

  • Reduces coupling between classes.
  • Simplifies testing (easy to substitute mocks).
  • Makes code more flexible and reusable.
<?phpclass Logger {    public function log($message) {        echo $message;    }}

class UserService { private $logger;

// Dependency is passed via the constructor public function __construct(Logger $logger) { $this->logger = $logger; }

public function register($email) { // ... registration logic $this->logger->log("User $email registered"); }}

$logger = new Logger();$service = new UserService($logger);?>


8. What are PHP traits and how do they differ from classes and interfaces?

Traits are a mechanism for code reuse in single inheritance languages like PHP.

  • A trait cannot be instantiated on its own.
  • It allows grouping methods that can be included in different classes.
  • Unlike interfaces, traits can contain method implementations.
  • Unlike classes, traits are not inherited; they are "used".
<?phptrait Loggable {    public function log($message) {        echo \"[LOG]: $message\";    }}

class User { use Loggable;}

class Order { use Loggable;}

$user = new User();$user->log('User created'); // [LOG]: User created?>


9. How does the __clone() method work and when is it needed?

The __clone() magic method is called on the cloned object after the shallow copy is performed. It is needed for deep copying of objects containing references to other objects.

<?phpclass Address {    public $city;}

class User { public $name; public $address;

public function __clone() { // Deep copy: create a new Address object $this->address = clone $this->address; }}

$user1 = new User();$user1->address = new Address();$user1->address->city = 'Moscow';

$user2 = clone $user1;$user2->address->city = 'Saint Petersburg';

echo $user1->address->city; // Moscow (without __clone it would be Saint Petersburg)?>


10. What is the difference between an abstract class and an interface?

This is a classic OOP question that tests understanding of abstraction.

  • Abstract class — can contain both abstract and regular methods with implementations. Can have properties. A class can inherit only one abstract class.
  • Interface — can only contain abstract methods (before PHP 8) or can contain default implementations (since PHP 8). Cannot have properties. A class can implement multiple interfaces.
<?phpinterface LoggableInterface {    public function log($message);}

abstract class BaseController { protected $db;

abstract public function handle();

public function render($view) { // rendering logic }}

class UserController extends BaseController implements LoggableInterface { public function handle() { // implementation }

public function log($message) { echo $message; }}?>

Blogs

Book Recommendations