100 questions for PHP developer interview. Answers with examples

100 questions for PHP developer interview. Answers with examples

1. What are links in PHP?

A means of accessing the contents of a single variable under different names

2. What are the basic operations using links?

There are three basic operations using references: assignment by reference, pass by reference, and return by reference.

// 1. Assignment by reference
$a = 5;
$b = &$a;   // Now $b "refers" to the same memory area as $a
$b = 10;
echo $a;   // Result: 10 (since $a and $b are the same value)

// 2. Passing by reference
function increment(&$value) {
    $value++;
}

increment($a); 
echo $a; // Result: 11

// 3. Return by reference
function &getValue() {
static $val = 0; // static variable retains value between calls
return $val;
}

// Get a reference to $val
$valRef = &getValue();
$valRef = 20;

// When we call the function again, we will see the changed value
echo getValue(); // Result: 20

3. Name the data types supported in PHP.

Scalar:

  • boolean (logical type)
  • integer (whole numbers)
  • double (fractional numbers)
  • string (strings)

Compound:

  • array (arrays)
  • object (objects)

Special:

  • resource (resources)
  • null

4. What is increment and decrement, what is the difference between prefix and postfix increment and decrement?

Decrement – increases the value of a variable by one
Increment – decreases the value of a variable by one

When using prefix notation, the variable is modified first, and then the return. When using postfix notation, it is the other way around: first the return, and then the variable is modified.
// Original value
$a = 5;

// 1. Prefix increment
// First $a is incremented by 1, then the result (6) is printed
echo ++$a; // Output: 6
echo "\n"; // Newline

// 2. Postfix increment
// First the current value (6) is returned, printed,
// then $a is incremented by 1 (to 7)
echo $a++; // Output: 6
echo "\n";

// Now $a = 7
echo $a; // Output: 7
echo "\n";

// 3. Prefix decrement
// First $a is decremented by 1 (i.e. from 7 to 6), then the result is printed
echo --$a; // Output: 6
echo "\n";

// 4. Postfix decrement
// First, the current value is returned (6), then $a is decremented (to 5)
echo $a--; // Output: 6
echo "\n";

// Now $a = 5
echo $a; // Output: 5

5. What is recursion?

A function that calls itself.

Recursive functions are often used to solve problems that can be broken down into smaller subproblems of similar types.

It is important to remember the base condition (breakpoint) to avoid infinite function calls.
/**
* Function to calculate the factorial of a number n.
* factorial(n) = n * factorial(n-1)
* Base condition: factorial(0) = 1 and factorial(1) = 1.
*/

function factorial($n) {
// Base case (exit condition)
if ($n <= 1) {
return 1;
}

// Recursive call: n * factorial(n - 1)
return $n * factorial($n - 1);
}

// Example of use
echo factorial(5); // Output: 120 (5 * 4 * 3 * 2 * 1)

6. What is the difference between =
== and === ?

= – assignment operator
== – operator defines non-strict comparison
=== – strict comparison operator. Equivalent comparison (variable types and their values ​​must strictly match)

7. What OOP principles do you know?

Encapsulation: Hiding an object’s internal state and functionality and providing access only through a public set of functions

Inheritance. The ability to create new abstractions based on existing ones

Polymorphism: The ability to implement inherited properties or methods in different ways within a set of abstractions

Some highlight +1 another principle

Abstraction: Modeling the required attributes and interactions of entities as classes to define an abstract representation of the system

OOP example
<?php
/**
* Abstract Animal class
* - Encapsulation: the $name property is protected and can be accessed
* via a constructor and a public getName() method.
* - Abstraction: the Animal class is abstract and describes
* only the general concept of an "animal" without a concrete implementation of speak().
*/
abstract class Animal
{
// Encapsulation: a protected property that is not directly accessible outside the class and its descendants
protected $name;

// Constructor for initializing the name
public function __construct($name)
{
$this->name = $name;
}

// Public method for getting the name value
public function getName()
{
return $this->name;
}

/**
* Abstract speak() method
* - The Animal class only declares the method but does not implement it,
* forcing descendants to implement their own logic.
*/
abstract public function speak();
}

/**
* Dog class
* - Inheritance: extends abstract class Animal.
* - Polymorphism: speak() method is overridden for "dog".
*/
class Dog extends Animal
{
public function speak()
{
return "Woof! My name is {$this->name}.";
}
}

/**
* Cat class
* - Inheritance: extends abstract class Animal.
* - Polymorphism: speak() method is overridden for "cat".
*/
class Cat extends Animal
{
public function speak()
{
return "Meow! I am {$this->name}.";
}
}

// Creating objects of different classes inherited from Animal
$dog = new Dog("Bobik");
$cat = new Cat("Murzik");

// Each animal implements the speak() method in its own way (polymorphism)
echo $dog->speak(); // Woof! My name is Bobik.
echo "\n";
echo $cat->speak(); // Meow! I am Murzik.
?>

Encapsulation

Hiding implementation details from external code. In the example, the \$name property is declared as protected, which does not allow it to be directly accessed from the outside (only through public methods or inside heirs).
Access to the state (the name of the animal) is carried out through the constructor or the getName() method. This allows you to control the correctness of the data and make changes to the logic of work without breaking the external code.

Inheritance

The Dog and Cat classes “inherit” from the common abstract class Animal. This means that they automatically receive the properties and methods of the base class (for example, \$name and getName()).
Polymorphism

Allows objects with the same set of methods (for example, speak()) to have different implementations.
In the code, both Dog and Cat implement the speak() method in their own way, while the signature (name and type of the method parameters) matches the abstract method from Animal.

Abstraction

The Animal class is declared as abstract. This means that objects cannot be created directly from it, but it serves as a “skeleton” or “template” for concrete implementations (“descendants”). Abstract methods (in this case, speak()) oblige all descendant classes to provide their own implementation.

8. What type system does PHP use? Describe the pros and cons.

A dynamic type system is used. Pros: for rapid development and prototyping. Cons: the presence of errors
and increased debugging.

9. What is the difference between the keywords: mysql_connect and mysql_pconnect?

mysql_pconnect() works similarly to mysql_connect() with two important differences.
First, when connecting, the function tries to find an already open (persistent) pointer to the same server with the same user and password. If one is found, it will be returned by the function, instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the script finishes. Instead, it will remain
working for future use ( mysql_close() also does not close persistent connections opened by
mysql_pconnect()).

10. What are interfaces? Do you use them? If so, tell us about it.

An abstract data type that defines contracts that commit methods to be implemented in classes that implement them.
In practice, interfaces contain function definitions (i.e., descriptions of their signatures) without their implementation.

Interfaces in PHP. Code examples open
Interfaces in PHP. Code examples
May 17, 2022
Roman-tk

11. What is an abstract class and how is it different from an interface?

An interface is a contract that must be implemented by a specific class. An abstract class is similar to a regular class, but differs in that it can contain abstract methods – methods without implementation, and an instance of an abstract class cannot be created. Interfaces are also implemented, and abstract classes are inherited.

12. Can an abstract class contain a private method?

yes

13. What visibility modifiers are there in PHP?

In PHP, there are three main access modifiers (visibility) for class properties and methods:

  • public – accessible from anywhere (outside the class, inside the class, in heirs).
  • protected – accessible only within the class itself and its descendants.
  • private – accessible only within the class where they are declared (not visible in descendants).

14. What magical methods do you know and how are they used?

Magic methods are special methods that override PHP’s default behavior when certain actions are performed on an object.

construct(), destruct(), call(), callStatic(), get(), set(), isset(), unset(), sleep(), wakeup(), serialize(), unserialize(), toString(),
invoke(), set_state(), clone() и __debugInfo()

Examples:

class Example
{
public function __construct()
{
echo "Constructor was called when object was created\n";
}

public function __destruct()
{
echo "Destructor was called when object was destroyed\n";
}
}

$obj = new Example();
// Output:
// Constructor was called when object was created
// (When script ends or "end of block" is reached)
// Destructor was called when object was destroyed
Class DynamicMethods
{
public function __call($name, $arguments)
{
echo "You called method '$name' with arguments: " . implode(", ", $arguments) . "\n";
}
}

$obj = new DynamicMethods();
$obj->someMethod("arg1", "arg2");
// Output:
// You called method 'someMethod' with arguments: arg1, arg2
class User
{
private $name;
private $email;

public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}

public function __toString()
{
// Return a string representation of the object
return "User: $this->name, Email: $this->email";
}
}

$user = new User("Ivan", "ivan@example.com");
echo $user;
// Output:
// User: Ivan, Email: ivan@example.com

15. What are generators and how to use them?

In PHP, an iterator is an object that allows you to iterate over the elements of a data set using constructs like foreach. One way to create your own iterator is to implement the Iterator interface in a class. Here is a very simplified example:


class MyCollection implements Iterator
{
private $items = [];
private $position = 0;

public function __construct(array $items)
{
$this->items = $items;
$this->position = 0;
}

// Resets the pointer to the beginning of the collection
public function rewind()
{
$this->position = 0;
}

// Returns the current item
public function current()
{
return $this->items[$this->position];
}

// Returns the key of the current item
public function key()
{
return $this->position;
}

// Move to the next item
public function next()
{
$this->position++;
}

// Checks if the current item exists
public function valid()
{
return isset($this->items[$this->position]);
}
}

// Usage example
$collection = new MyCollection(["apple", "banana", "orange"]);

foreach ($collection as $key => $value) {
echo "{$key} => {$value}\n";
}

16. What does the yield operator do?

In its simplest form, the “yield” statement can be thought of as a “return” statement, except that instead of terminating the function, “yield” only pauses its execution and returns the current value, and the next time the function is called, it will resume execution from where it left off.

function rangeGenerator($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i; 
    }
}

17. What are traits? Alternative solution? Give an example.

A trait is a mechanism for ensuring code reuse in languages ​​that only support single inheritance, such as PHP. A trait is intended to alleviate some of the limitations of single inheritance by allowing the developer to reuse sets of methods freely, across multiple independent classes and implemented using different class architectures.

In PHP, one class can inherit from only one parent class (single-point or single-instance inheritance).
trait LoggerTrait
{
    public function log($message)
    {
        echo "[LOG]: $message\n";
    }
}

class MyClass
{
    use LoggerTrait;
}

$obj = new MyClass();
$obj->log("Message from trait!");

18. Describe the behavior when using traits with the same field and/or method names.

When using multiple traits with the same methods, a conflict occurs. The conflict is resolved using the insteadOf operator.

Also, if the child class has the same overridden method as the base class, and the trait has the same name, the call order is as follows:

  • Calling a child method
  • Calling a trait method
  • Call from parent class

class Base
{
    public function sayHello()
    {
        echo 'Hello ';
    }
}

trait SayWorld
{
    public function sayHello()
    {
        echo 'SayWorld!';
    }
}

trait SayHello
{
    public function sayHello()
    {
        echo 'SayWorld!';
    }

    private function saySome()
    {
        echo 'SaySome!';
    }
}

class MyHelloWorld extends Base
{
    use SayWorld, SayHello {
       
	   // Specify that the sayHello method from the SayHello trait
		// is used instead of the similar method from SayWorld
        SayHello::sayHello insteadOf SayWorld;
    }

    public function sayForTrait()
    {
        // Call the private method saySome() of the trait inside the class
        $this->saySome();
    }
}

// Тестируем
$o = new MyHelloWorld();
$o->sayHello();    //  SayWorld!
$o->sayForTrait(); // SaySome!

19. Will private methods of trait be available in class?
Yes

20. Is it possible to compose traits into a trait?

Yes, in PHP you can use (compose) traits inside other traits. To do this, you specify the keyword use inside the trait, just like inside a class.

Traits in PHP. Code examples open
Traits in PHP. Code examples
May 17, 2022
Mironofff

21.Explain about error and exception handling (try catch, finally and throw).

Exceptions in PHP can be thrown or caught. Code can be enclosed in a try block to facilitate the handling of potential exceptions. Each try block must have at least one corresponding catch or finally block.

Exceptions are needed to provide informative notification about an application error.

Exception in php. Code examples open
Exception in php. Code examples
June 23, 2022
Roman-tk

22. What is type hinting, how does it work, why is it needed?

Is a mechanism that allows you to specify what type of value is expected in function/method arguments and what type it should be returned. By default, PHP is a dynamically (and weakly) typed language, but having typing gives you more control over what data is used in your code.

More
//Argument Types
function addNumbers(int $a, int $b): int
{
return $a + $b;
}

echo addNumbers(2, 3); // 5
echo addNumbers("4", 5); // Without strict_types "4" is converted to a number;

// in strict mode (declare(strict_types=1)) we get TypeError


//Return Type Declaration
function getMessage(): string
{
return "Hello, world!";
}

echo getMessage(); // Hello, world!

23. What are namespaces and why are they needed?

A namespace in PHP is a way to group classes, interfaces, traits, functions, and constants under a unique “address.” Essentially, it is a means of organizing (structuring) code and resolving name conflicts.

Namespace in PHP. Code example open
Namespace in PHP. Code example
May 16, 2022
Roman-tk

24. Comparison of variable values ​​in PHP and pitfalls? Type casting. What has changed in PHP 8 in this context?

Comparing values ​​in PHP can produce unexpected results due to implicit type juggling.

"42" == 42 // true (the string "42" is converted to the number 42)
"abc" == 0 // true (the string "abc" is converted to 0)
"" == false // true (the empty string is converted to false)

//=== (strict comparison): values ​​are compared by both type and value

"42" === 42    // false 
"abc" === 0    // false
"" === false   // false

With ==, PHP tries to convert the string to a number. If the string does not start with a number (or +/– sign), it turns into 0.

"abc" == 0  // true
"1abc" == 1 // true
When comparing an array to any non-array, == forces the array to boolean = true (since a non-empty array is equivalent to true), and the other side can also become true if it is also “non-empty”. Such nuances make debugging difficult.
What has changed in PHP 8?
PHP 8 has refined the logic for defining Numeric Strings. Key points:

  • Previously, a string like “123abc” could be partially interpreted as the number “123”, now PHP more clearly distinguishes between a leading numeric string and a “completely non-numeric” string.
  • A “leading numeric” string will still be converted to a number during a loose comparison ( “123abc” == 123 → true ), while a “completely non-numeric” string (“abc”) will be converted to 0.
  • By enabling strict types (declare(strict_types=1)), many operations that previously silently converted now throw a TypeError when there was an obvious type mismatch.
  • Union types allow you to specify that a parameter or return value can be of multiple types at once. For example, int|string means “either an int or a string is accepted or returned.”

    		unction formatValue(int|string $value): int|string
    {
    if (is_int($value)) {
    return "Number: " . $value; // Return string
    }
    return (int)$value; // Return int
    }
    
    echo formatValue(42); // "Number: 42" (string)
    echo "\n";
    echo formatValue("123"); // 123 (int)
    		
  • Previously, the shorthand ?Type (equivalent to Type|null) was often used to mean “can be type X or null”. Since PHP 8, you can explicitly write Type|null:

    		function getName(): string|null
    {
        
        return rand(0, 1) ? "John" : null;
    }
    		
  • In PHP 8+, it is possible to specify false as part of a union type, or even as a separate type:

    	function findItem(array $items, int $id): Item|false
    {
        return $items[$id] ?? false;
    }
    
  • Since PHP 8, you can specify static as a return type in a method signature. This means that the method will return an instance of the called class (late static binding), not the parent class:

    	class Base
    {
    public static function create(): static
    {
    // Return the instance of the class on which the method is called
    return new static();
    }
    }
    
    class Child extends Base
    {
    }
    
    $base = Base::create(); // $base will be an object of class Base
    $child = Child::create(); // $child will be an object of class Child
    	
  • The mixed type first became “official” in PHP 8 (previously it was only mentioned in the documentation). It means that the value can be of any type: int, string, bool, array, object, resource, null, etc.

    	function doSomething(mixed $value): void
    {
        var_dump($value);
    }
    
    doSomething(123);        // int
    doSomething("text");     // string
    doSomething(null);       // null
    doSomething(new StdClass); // object
    	

25. How does session work in PHP, where is it stored, how is it initialized?

Sessions are a simple way to store information for individual users with a unique session ID. This can be used to maintain state between page requests. Session IDs are typically sent to the browser via a session cookie and are used to retrieve existing session data. The absence of a session ID or session cookie tells PHP to create a new session and generate a new session ID.

A file is created in the directory on the server that is specified in the php configuration

26. Superglobal arrays. Which ones do you know? How did you use them?

There are several superglobal arrays in PHP, the most common ones are:

$_SERVER
Contains information about the server and environment, such as hostname, request method, script path, etc.

// Print the request method (GET, POST, etc.)
echo $_SERVER['REQUEST_METHOD'];

// Path to the executable script
echo $_SERVER['SCRIPT_FILENAME'];

$_GET

Stores data passed via the Query String.
Example: if the URL looks like http://example.com/page.php?user=John&id=5, then:

cho $_GET['user']; // "John"
echo $_GET['id'];   // "5"

$_POST

Stores data sent using the POST method (usually from HTML forms).

$_REQUEST

Combines data from $_GET, $_POST and $_COOKIE.

27. Compare include vs required, include_once vs required_once.

include – does not return an error if there is no script in the included file, require does. include_once, required_once – includes the file once.

28. What does algorithm complexity mean?

The complexity of an algorithm is a quantitative characteristic that indicates how much time or how much memory is required to execute the algorithm. Оn) – is denoted as big O.

29. What is a closure in PHP? Give an example.

Closures in PHP represent an anonymous function that can use variables from its local environment. Unlike regular anonymous functions, closures in PHP can use the use statement.

function makeCounter()
{
    $count = 0;

    return function() use (&$count) {
        $count++;
        return $count;
    };
}

$counter = makeCounter();

echo $counter(); // 1
echo $counter(); // 2
echo $counter(); // 3

In the example, the anonymous function (closure) is returned from makeCounter(), but still has access to the $count variable within itself.

The use (&$count) keyword means that the $count variable will be passed by reference and its value will be preserved between calls.

30. What is the difference between closure in PHP and JavaScript?

In PHP, closure can only be used with anonymous functions, while in JavaScript, closure can be created with any function. Also, in JavaScript, closure can be used to create private variables and methods, which is not possible in PHP.

31. What is late binding? Explain the behavior and usage of static.

Late (or “late static”) binding in PHP is a mechanism that allows calls to inherited static methods to be based not on the class in which the method was defined, but on the class from which the method was called.

In other words, instead of a “hard” binding to the current one (self::), a “dynamic” binding to the caller (static::) is used.

class A
{
    public static function who()
    {
        echo __CLASS__ . "\n";
    }

    public static function test()
    {
        //Use late static binding
        static::who();
    }
}

class B extends A
{
    public static function who()
    {
        echo __CLASS__ . "\n";
    }
}

B::test(); 
// Result: "B"

32. How to override session storage?

In the configuration option session.save_handler.

33. Tell us about the SPL library (Reflection, autoload, data structures).

SPL (Standard PHP Library) is a standard PHP library that contains a set of interfaces, classes and functions that solve typical tasks. It includes:

  • SPL-Autoload – provides mechanisms for automatic class loading via spl_autoload_register().
  • SPL-Data Structures – a set of ready-made classes for working with queues, stacks, heaps, trees (for example, SplStack, SplQueue, SplHeap, SplDoublyLinkedList, etc.). These are efficient implementations of data structures written in C, so they are generally faster than custom PHP classes.
  • Iterator Interfaces – Iterator, IteratorAggregate, SeekableIterator and other interfaces that make it easy to create your own iterators. RecursiveIterator, RecursiveDirectoryIterator, etc. – for recursive traversal of the file system structure.
  • Reflection – a separate but often mentioned in the context of SPL is the class system (ReflectionClass, ReflectionFunction, ReflectionProperty, etc.). Allows you to analyze the structures of classes, methods, properties, functions during execution. Used, for example, when writing frameworks (for dynamically calling methods, reading annotations, etc.)
  • SPL exceptions (LogicException, InvalidArgumentException, etc.) provide more precise error semantics.
Examples
function myAutoload($className)
{
// Example of simple file inclusion by class name
require_once __DIR__ . "/classes/" . $className . ".php";
}

spl_autoload_register('myAutoload');

Now when creating a new object new SomeClass(), if the class is not found, PHP will call myAutoload() and try to include the corresponding file.

$stack = new SplStack();
$stack->push("First");
$stack->push("Second");

echo $stack->pop(); // "Second"

SplStack, SplQueue, SplHeap and other classes provide ready-made methods without the need to write your own stack/queue logic.

34. Tell us about the SOLID principles.

SOLID is a set of five principles of object-oriented design proposed by Robert Martin (Uncle Bob). In short:

  1. Single Responsibility Principle – each class (or module) should have only one reason to change. In other words, the class does one thing and does it well.
  2. Open/Closed Principle – software entities should be open to extension but closed to modification. When it is necessary to add functionality, it is better to extend the existing code (through inheritance, composition, etc.) without changing the internal implementation.
  3. Liskov Substitution Principle – objects of child classes should be able to replace objects of the parent class without any problems. The successor must not break the logic expected by the parent type.
  4. Interface Segregation Principle – many client-specific interfaces are better than one “fat” interface.” Interfaces should be narrowly focused and not force implementations to contain “extra” methods.
  5. Dependency Inversion Principle – Dependencies within a system should be built from abstractions, not from concrete implementations. Top-level modules should not depend on lower-level modules; they should all depend on abstractions (interfaces).

Following SOLID principles makes the system more flexible, extensible and simplifies code maintenance.

35. Explain about GRASP templates.

GRASP (General Responsibility Assignment Software Patterns) is a set of principles for distributing responsibilities between objects. They help determine which class or object should be given a specific responsibility (operations, data storage, etc.). There are nine main GRASP patterns:

  1. Information Expert –
  2. Information Expert – assign responsibility to the class that contains the information needed to complete the task.
  3. Creator – a class that aggregates or uses objects of another class, or stores their data, should be responsible for their creation (initiation)
  4. Controller – organize the application logic through a controller object that receives requests from the outside world (UI) and delegates tasks to models
  5. Lov Supling – minimize interdependencies between classes. The less classes know about each other’s internals, the easier they are to maintain and reuse.
  6. High Cohesion – The class should be focused on solving a narrow range of problems (internal coherence). The more closely related the responsibilities within a class are, the easier they are to understand, change, and reuse.
  7. Polymorphism – Type-specific operations must be performed differently by objects of different types using a single interface. This allows you to call the same method on different classes, and each class implements it differently.
  8. Indirection – introduce an intermediate object to reduce direct dependencies between other objects. Such a “gasket” (mediator, facade) reduces the adhesion of the class
  9. Pure Fabrication – An auxiliary class or object that is not directly related to a domain, but is allocated to facilitate design. That is, the artificial creation of a separate “service” or “utility” to unload domain objects
  10. Protected Variations – Stable interfaces or abstract ones help protect against changes by hiding implementation details. This way, changes in one part of the system do not break another.

36. Tell us about Dependency Injection: what are DI containers? What are the implementation options?

Dependency Injection (DI) is a pattern where dependencies (objects/services) are passed to a class from outside (via a constructor, methods, or properties) instead of the class creating these objects itself. This improves testability and flexibility, as it makes it easier to replace and substitute dependencies.

DI container (IoC container)

A DI container is a special object/system that manages the creation of instances of classes and their dependencies.

The container can:

  • Store the configuration of how to create classes (what constructor arguments, what dependencies are required).
  • Automatically “inject” dependencies into the right places (constructors, setters).

37.What do you know about MVC?

MVC (Model-View-Controller) is a design pattern that divides an application into three components:

  • Model – Responsible for business logic, working with data, and interaction with the database. Contains classes that describe the subject area (products, users, etc.), methods for selecting, changing data and validation rules.
  • View – Responsible for displaying data to the user (HTML, CSS, templates). Does not contain business logic itself; receives data from the Model (or Controller) and displays it on the screen.
  • Controller – Accepts incoming requests (for example, from routing), calls the necessary Models, generates data and passes it to the View. Coordinates interactions between the Model and the View.

38. What do you know about GoF patterns?

The GoF (Gang of Four) patterns are 23 classic design patterns described in the book Design Patterns: Elements of Reusable Object-Oriented Software (authors: Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides). They are divided into three broad categories:

  1. Creational
    Determine how to create objects so that the system is not tightly tied to specific classes.
    Examples: Singleton, Factory Method, Abstract Factory, Builder, Prototype.
  2. Structural
    Define how objects and classes form larger structures (composition, inheritance).
    Examples: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
  3. Behavioral
    Describe the interaction of objects, the distribution of responsibilities and ways of organizing behavior in the system.
    Examples: Observer, Strategy, Command, Iterator, State, Visitor, Mediator, Memento, Template Method, Chain of Responsibility, Interpreter.

39. What do you know about the patterns used in ORM?

Active Record and Data Mapper are two main patterns used when creating ORM (Object-Relational Mapping):

Active Record

  • Each model is closely associated with a specific table in the database.
  • The model object can load, save and delete itself (it contains methods for CRUD operations).
  • Example: the User class has properties corresponding to the fields of the users table, and methods save(), delete(), etc.
  • Pros: ease of use, speed of development.
  • Cons: strong binding of logic to the database structure (not so flexible for complex business rules).

Data Mapper

  • The Mapper layer is responsible for mapping business logic objects to database tables/records.
  • Domain model objects (Entity) do not know how they are stored in the database; the mapper takes care of all the logic of working with the database.
  • Pros: good isolation of business logic from storage details, more convenient to implement complex scenarios.
  • Cons: slightly more complex implementation, more code, and the need to write or use separate mappers.

40. Write an example of implementing the Singleton pattern in PHP.

class Singleton
{
    // Stores the single instance of this class
    private static $instance = null;

    // Private constructor to prevent direct instantiation
    private function __construct()
    {
        // Initialization code
    }

    // The static method to get (or create) the single instance
    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // Disallow cloning the instance
    private function __clone() {}

    // Disallow unserializing the instance
    private function __wakeup() {}

    // Example method
    public function doSomething(): void
    {
        echo "Singleton is doing something!\n";
    }
}

// Usage
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

// Both will point to the same instance
$instance1->doSomething();
var_dump($instance1 === $instance2); // bool(true)

41. What is Docker? How does it work?

Docker is a platform that allows you to package an application with all its environment and dependencies into a container, and then deliver and run it on the target system. An application packaged in a container is isolated from the operating system and other applications.

42. Tell us about the SSH protocol.

SSH (from English secure shell) is a secure network protocol for remote server management via the Internet.
A network protocol of the application layer, designed for secure remote access to UNIX systems. This protocol is effective because it encrypts all information transmitted over the network.

43. What is PDO?

PDO PHP Data Objects) is a PHP extension that implements interaction with databases using objects. The benefit is that there is no binding to a specific database management system

44. What’s new in PHP 8?

What's new in PHP 8? open
What's new in PHP 8?
January 20, 2025
Timo Tont

45. What is the difference between GET and POST?

The main difference between the GET and POST methods is the way they transfer data. A GET request transfers data in the URL as name-value pairs (in other words, via a link), while a POST request transfers data in the body of the request.

46. Is there a difference between single and double quotes?

Strings with double and single quotes differ in: Variable substitution: the value of a variable is substituted into a string with double quotes, but not into a string with single quotes.

47. What are cookies and why are they used?

A small piece of data sent by a web server and stored on the user’s computer. The web client (usually a web browser) sends this piece of data to the web server as part of an HTTP request each time it tries to open a page on the corresponding site.

48. What cannot be stored in cookies and why?

Confidential data. No, because there is a risk that the cookie will be obtained by an attacker.

49. What development environment do you prefer and why?

IDE PHPStorm, VSCODE

50. What command to add changes?

git add . 

51. What command to use to commit changes?

git commit -m

52. What command to send changes to a remote repository?

git push origin <branch_name>

53. What are the advantages of version control system?

  • This is useful when working together in a team.
  • This helps integrate automation code into the CI/CD pipeline.
  • This helps in early testing of a particular feature by checking out a feature branch.

54. What is the difference between git merge and git rebase?

Both git merge and git rebase integrate changes from one branch into another branch. Git rebase applies all the feature branch changes on top of the master branch, creating a new commit for each of its previous commit messages. The rebase command modifies the commit history and creates commits on top of the master branch again.

55. What is a transaction in SQL?

A transaction is a sequence of SQL statements that is considered as a single action on the database.

56. What is normalization in Data Base?

Normalization is the process of organizing data in a database, which involves creating tables and establishing relationships between them according to rules that provide data security and make the database more flexible by eliminating redundancies and inconsistent dependencies.

57. What is denormalization? What is it for?

Denormalization is the deliberate bringing of a database structure into a state that does not meet the normalization criteria, usually carried out with the aim of speeding up read operations from the database by adding redundant data.

58. What are the types of relationships in a database?

In relational databases, relationships between tables are defined by relationship types. The main types are:

One-to-One

Each record in table A has at most one corresponding record in table B and vice versa.
Example: Users table and Profiles table, where each user has one profile.

One-to-Many

One record in table A corresponds to several records in table B, but each record in table B corresponds to only one record in table A.
Example: one author can have several books (the Authors table is related to the Books table).

Many-to-One

This is the opposite of one-to-many: multiple records in table A reference one record in table B.
Example: multiple books by the same author.

Many-to-Many

Several records in table A may correspond to several records in table B and vice versa.
To implement such relationships, an intermediate (linking) table is usually created.
Example: students and courses – one student can enroll in several courses, one course can include several students.

60. What does it mean when a DBMS maintains referential integrity of relationships?

The goal of maintaining, or ensuring referential integrity, is to prevent or eliminate the violation of the correctness of foreign key values when changes are made to the database by correcting the foreign key values, if possible, or canceling the editing operation if such a correction is not possible.

61. What are primary and foreign keys? (DB)

Primary key: a set of specific attributes that are unique to each record. The primary key is designated as primary key.

Foreign key (FK for short). Provides an unambiguous logical connection between tables of one database.

63. What is the difference between primary and unique keys?

A primary key is used to uniquely identify records in a table, while a foreign key is used to join two tables together.

64. What are the types of JOIN and how do they differ?

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2025
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation