Mastering the PHP Developer Interview: 100+ Technical Questions Answered. 1-15.
Table of contents
- 1. What are references?
- 2. What are the main operations involving the use of references?
- 3. Name the data types supported in PHP.
- 4. What are increment and decrement, and what is the difference between prefix and postfix increment and decrement?
- 5. What is recursion?
- 6. What is the difference between =, == , and === ?
- 7. What Object-Oriented Programming (OOP) principles do you know?
- 8. What type system is used in PHP? Describe the pros and cons.
- 9. What is the difference between the keywords mysql_connect and mysql_pconnect?
- 10. What are interfaces? Do you use them? If yes, tell me about it.
- 11. What is an abstract class, and how does it differ from an interface?
- 12. Can an abstract class contain private methods?
- 13. What visibility modifiers exist in PHP?
- 14. What magic methods do you know, and how are they used?
- 15. What are generators and how do you use them?
Navigate the core of PHP knowledge vital to acing technical interviews. Explore references, data types, increment and decrement, recursion, comparison operators, OOP principles, PHP's type system, interfaces, abstract classes, visibility modifiers, magic methods, and generators. These 15 questions lay the foundation for excelling in PHP interview scenarios.
1. What are references?
In PHP, references allow you to create aliases for variables. This means that two variables can point to the same value in memory. Changes made to one variable will also be reflected in the other variable, as they both refer to the same memory location.
$a = 5;
$b = &$a; // $b becomes a reference to $a
$b = 10; // Changing $b also changes $a
echo $a; // Output: 10
In this example, $b
becomes a reference to $a
, and any changes made to $b
will also affect $a
. As a result, the output will be 10, since the values of both variables were updated.
2. What are the main operations involving the use of references?
The main operations involving references in PHP include:
Creating References: You can create a reference by using the &
symbol before a variable. This makes the new variable a reference to the original variable.
`$a = 5; $b = &$a; // $b becomes a reference to $a`
Assigning References: You can assign a reference to another reference, creating a chain of references.
`$a = 5; $b = &$a; $c = &$b; // $c also becomes a reference to $a`
Unset References: You can break the reference by using the unset()
function.
unset($b); // $b is no longer a reference to $a`
Function Arguments by Reference: You can pass variables to functions by reference. Changes made within the function will affect the original variables.
function modify(&$value) {
$value *= 2;
}
$number = 7;
modify($number); // $number is now 14
Returning Values by Reference: Functions can also return values by reference. This can be useful for modifying variables outside the function.
function &getReference() {
$value = 42;
return $value;
}
$result = &getReference(); // $result is now a reference to $value
Reference Counting: PHP uses reference counting to manage memory. When a variable's reference count reaches zero (no references point to it), the memory is freed.
References in PHP are a powerful tool, but they can also lead to unexpected behavior if not used carefully. Understanding how references work can help you avoid potential pitfalls.
3. Name the data types supported in PHP.
PHP supports several data types, including:
Scalar
Integer: Represents whole numbers, both positive and negative.
$num = 42;
Float (Double): Represents decimal numbers with floating-point precision.
$pi = 3.14;
String: Represents sequences of characters.
$text = "Hello, World!";
Boolean: Represents true or false values.
$isTrue = true;
$isFalse = false;
Complex
Array: Represents an ordered collection of values.
$fruits = ["apple", "banana", "orange"];
Object: Represents instances of classes.
class Car {
// Properties and methods
}
$carObject = new Car();
Special
Resource: Represents external resources, such as database connections.
$dbConnection = mysqli_connect("localhost", "username", "password", "database");
NULL: Represents the absence of a value.
$noValue = null;
Callable: Represents a function or method that can be called.
$func = function($x) { return $x * $x; };
Iterable: An iterable is a data type that can be traversed or looped through. Iterables include arrays, objects implementing the Traversable
interface, and other data structures that can be iterated over.
// Example array
$fruits = ['apple', 'banana', 'orange', 'grape'];
// Looping through an array using a foreach loop
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Example object implementing Traversable interface
class MyIterator implements Iterator {
private $position = 0;
private $data = ['one', 'two', 'three'];
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->data[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->data[$this->position]);
}
}
$iterator = new MyIterator();
// Looping through an object implementing the Iterator interface
foreach ($iterator as $key => $value) {
echo "$key: $value\n";
}
4. What are increment and decrement, and what is the difference between prefix and postfix increment and decrement?
Increment and decrement are operations used to increase or decrease the value of a variable by 1. In PHP, the increment operator is ++
, and the decrement operator is --
.
Prefix Increment/Decrement: When the increment (++
) or decrement (--
) operator is placed before the variable, it is called the prefix increment/decrement. In this case, the value of the variable is changed before it's used in an expression.
$number = 5;
$result = ++$number; // Prefix increment
// $number is now 6, $result is 6
Postfix Increment/Decrement: When the increment (++
) or decrement (--
) operator is placed after the variable, it is called the postfix increment/decrement. In this case, the value of the variable is used in an expression, and then it is changed.
$number = 5;
$result = $number++; // Postfix increment
// $number is now 6, $result is 5
The key difference between prefix and postfix increment/decrement is the timing of when the variable's value is changed. Prefix changes the value before using it, while postfix changes it after using it.
5. What is recursion?
Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. In other words, it's a process in which a function performs some operation on a particular input and then calls itself with a modified input. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems.
To implement recursion, a base case and a recursive case are defined:
Base Case: This is the condition in which the function stops calling itself and returns a result. It prevents infinite recursion.
Recursive Case: This is the part of the function where it calls itself with a modified input, moving closer to the base case.
A classic example of recursion is calculating the factorial of a number:
function factorial($n) {
// Base case
if ($n == 0 || $n == 1) {
return 1;
}
// Recursive case
return $n * factorial($n - 1);
}
$result = factorial(5); // Result: 5 * 4 * 3 * 2 * 1 = 120
In this example, the factorial()
function calls itself with a smaller value until it reaches the base case of n == 0
or n == 1
. Recursion can be a powerful technique, but it's important to ensure that base cases are properly defined to avoid infinite loops.
6. What is the difference between =, == , and === ?
=
is used for variable assignment.==
is used to compare values for equality.===
is used to compare both values and data types for identity.
7. What Object-Oriented Programming (OOP) principles do you know?
Encapsulation: Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on that data into a single unit, called a class. Access to the data and methods is controlled by access modifiers (public, private, protected), allowing for better data protection and more organized code.
Abstraction: Abstraction involves creating simplified representations of complex reality. It allows you to focus on the essential aspects of an object while hiding unnecessary details. Abstract classes and interfaces in PHP are used to define common methods and properties that can be shared by different subclasses.
Inheritance: Inheritance enables a new class (subclass or derived class) to inherit properties and behaviors from an existing class (superclass or base class). This promotes code reuse and allows you to create specialized classes that extend the functionality of a general class.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. This allows you to write more generic code that can work with objects of different types. Polymorphism is often achieved through interfaces or abstract classes in PHP.
8. What type system is used in PHP? Describe the pros and cons.
PHP uses a dynamic weakly typed system of data types. Here's what that means and its pros and cons:
Dynamic Typing:
In a dynamic typing system, variables are not bound to a specific data type during declaration. They can change their data type during runtime.
For example, a variable can hold an integer at one point and then hold a string at another point in the program.
Weak Typing:
In a weak typing system, there's some flexibility in how data types are treated in operations. PHP allows operations between different data types without explicit type conversion in some cases.
For example, concatenating a string and an integer can result in automatic type conversion.
Pros:
Flexibility: Dynamic typing allows for flexibility in coding. You can change the data type of a variable without much hassle, making coding quicker and easier.
Simplified Syntax: Weak typing can lead to more concise code, as type conversion is often handled automatically.
Rapid Development: Dynamic typing can facilitate rapid prototyping and development, as you don't need to specify types explicitly.
Cons:
Error Detection: Weak typing can lead to subtle bugs and errors that might not be caught until runtime. Type-related issues might not be immediately apparent.
Maintenance Challenges: Code maintenance can become challenging as the complexity of a project grows. It might be harder to understand how data types change during the execution of a program.
Debugging Complexity: Debugging can be trickier due to unexpected type conversions and implicit behavior.
Performance Impact: Dynamic typing and automatic type conversion can introduce performance overhead, as the interpreter needs to handle type checks and conversions.
Readability and Predictability: Weak typing can make code less readable and predictable, as the behavior of an operation might not be immediately apparent.
In recent PHP versions, there's been a push towards stricter typing with the introduction of type declarations and strict mode. This allows developers to specify expected parameters and return types for functions and methods, offering a balance between the flexibility of dynamic typing and the benefits of more strict typing.
9. What is the difference between the keywords mysql_connect
and mysql_pconnect
?
Both mysql_connect
and mysql_pconnect
are functions used in older versions of PHP to establish connections to a MySQL database. However, they have different behaviors regarding how the connection is managed:
mysql_connect:
mysql_connect
is used to establish a regular (non-persistent) connection to the MySQL database.Each time you call
mysql_connect
, it opens a new connection to the MySQL server. After you're done using the connection, you need to close it usingmysql_close
to free up resources.Regular connections are suitable for scenarios where you don't need to maintain a long-lived connection to the database or when you want more control over when the connection is opened and closed.
$connection = mysql_connect($server, $username, $password); // Use the connection mysql_close($connection);
mysql_pconnect:
mysql_pconnect
is used to establish a persistent connection to the MySQL database.Persistent connections are maintained in a connection pool and are reused across multiple requests. They aren't closed after each request, which can improve performance by avoiding the overhead of establishing a new connection every time.
However, persistent connections can also lead to resource exhaustion if not managed properly. They should be used carefully and closed when they're no longer needed.
$connection = mysql_pconnect($server, $username, $password); // Use the connection // No need to explicitly close the connection with mysql_pclose
Important notes:
The
mysql
extension used with these functions is deprecated as of PHP 5.5.0 and has been removed in PHP 7.0.0. It's recommended to use themysqli
orPDO
extensions for database interactions in modern PHP versions.Persistent connections (
mysql_pconnect
) are generally discouraged due to potential resource issues. Using connection pooling libraries and proper connection handling is often a better approach in modern PHP applications.
10. What are interfaces? Do you use them? If yes, tell me about it.
Interfaces in PHP define a contract that classes can follow by implementing the methods declared in the interface. An interface defines the method signatures that must be present in the classes that implement it, but it does not provide the implementation details. This allows you to ensure that different classes have the same methods, promoting a consistent structure in your codebase.
For example, consider an interface for a basic shape:
interface Shape {
public function calculateArea();
public function calculatePerimeter();
}
class Circle implements Shape {
// Implementation of methods for a circle
}
class Square implements Shape {
// Implementation of methods for a square
}
In software development, interfaces help me achieve a few important goals:
Code Organization: Interfaces allow me to organize my code by clearly defining contracts that classes need to adhere to. This helps create a more maintainable and understandable codebase.
Polymorphism: Interfaces enable polymorphism, where different classes that implement the same interface can be used interchangeably. This is particularly useful when dealing with different implementations of common functionality.
Dependency Injection: I often use interfaces to implement dependency injection. By coding to interfaces rather than concrete implementations, I can easily swap out components without affecting the rest of the code.
Collaboration: Interfaces are valuable when collaborating on projects with a team. They provide a clear understanding of what methods a class should have and help maintain consistency across the codebase.
11. What is an abstract class, and how does it differ from an interface?
Abstract Class: An abstract class in PHP is a class that cannot be instantiated on its own. It's designed to be a base class for other classes to inherit from. Abstract classes can contain both regular methods with implementations and abstract methods that have no implementation in the abstract class itself. Subclasses that inherit from an abstract class must provide implementations for all abstract methods. Abstract classes can also have properties and methods with regular implementations.
Here's an example of an abstract class:
abstract class Animal {
abstract public function makeSound(); // Abstract method with no implementation
public function eat() {
echo "The animal is eating.\n";
}
}
Interface: An interface defines a contract that classes must adhere to. It only specifies method signatures without providing implementations. A class can implement multiple interfaces, and those classes must implement all the methods declared in those interfaces.
Here's an example of an interface:
interface Vehicle {
public function startEngine(); // Method signature
public function stopEngine(); // Method signature
}
Differences:
Instantiation:
Abstract classes cannot be instantiated directly. They need to be subclassed.
Interfaces cannot be instantiated at all. They are meant to be implemented by classes.
Method Implementation:
Abstract classes can have both abstract methods and methods with implementations.
Interfaces can only have method signatures, no implementations.
Multiple Inheritance:
A class can only inherit from one abstract class.
A class can implement multiple interfaces.
Purpose:
Abstract classes are used when you want to provide a common base with some default behavior for subclasses. They allow you to share code between related classes.
Interfaces are used to define a contract that multiple unrelated classes can adhere to. They enforce a specific API without enforcing an inheritance hierarchy.
In summary, abstract classes and interfaces serve different purposes. Abstract classes provide a base for subclasses to inherit from, while interfaces define a contract that classes must adhere to, regardless of their inheritance hierarchy.
12. Can an abstract class contain private methods?
Yes, an abstract class can indeed contain private methods. However, these private methods remain visible solely within the abstract class itself and are inaccessible for inheritance or invocation from its derived (child) classes.
abstract class AbstractClass {
private function privateMethod() {
echo "This is a private method.\n";
}
abstract public function abstractMethod();
}
class ChildClass extends AbstractClass {
public function abstractMethod() {
// Implement the abstract method
}
public function callPrivateMethod() {
$this->privateMethod(); // This will result in an error
}
}
$child = new ChildClass();
$child->callPrivateMethod(); // Results in an error: Cannot access private method
In this provided example, attempting to call the private method privateMethod
from the ChildClass
leads to an error because private methods are not inherited and cannot be accessed beyond their declaration within the class.
13. What visibility modifiers exist in PHP?
PHP has three visibility modifiers that determine the access level of class properties and methods within classes. These modifiers are:
public: Members declared as public are accessible from anywhere, both inside and outside the class. They have no access restrictions.
protected: Members declared as protected are accessible within the class where they are defined and within any subclasses (derived classes) of that class. They are not directly accessible from outside the class hierarchy.
private: Members declared as private are only accessible within the class where they are defined. They are not accessible from subclasses or from outside the class.
Here's an example demonstrating the use of visibility modifiers:
class Example {
public $publicProperty = "This is a public property";
protected $protectedProperty = "This is a protected property";
private $privateProperty = "This is a private property";
public function publicMethod() {
echo "This is a public method.\n";
}
protected function protectedMethod() {
echo "This is a protected method.\n";
}
private function privateMethod() {
echo "This is a private method.\n";
}
}
$example = new Example();
echo $example->publicProperty; // Accessible
// echo $example->protectedProperty; // Not accessible
// echo $example->privateProperty; // Not accessible
$example->publicMethod(); // Accessible
// $example->protectedMethod(); // Not accessible
// $example->privateMethod(); // Not accessible
14. What magic methods do you know, and how are they used?
Magic methods in PHP are predefined methods with special names that are triggered in response to certain actions or events, such as object instantiation, property access, method calls, and more. They allow you to customize the behavior of classes and objects in various ways. Here are some commonly used magic methods:
__construct()
: This magic method is called automatically when an object is instantiated. It's used for initialization tasks when creating an instance of a class.
class MyClass {
public function __construct() {
echo "Object instantiated.\n";
}
}
$object = new MyClass(); // Output: Object instantiated.
__destruct()
: This magic method is called automatically when an object is no longer referenced or explicitly destroyed. It's used for cleanup tasks before an object is removed from memory.
class MyClass {
public function __destruct() {
echo "Object destroyed.\n";
}
}
$object = new MyClass();
unset($object); // Output: Object destroyed.
__get()
and __set()
: These methods are called when getting or setting inaccessible properties.
class MyClass {
private $data = [];
public function __get($name) {
return $this->data[$name];
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$object = new MyClass();
$object->property = "Value";
echo $object->property; // Output: Value
__call()
: This method is invoked when calling inaccessible methods.
class MyClass {
public function __call($name, $arguments) {
echo "Calling method '$name' with arguments: " . implode(', ', $arguments) . "\n";
}
}
$object = new MyClass();
$object->nonExistentMethod("arg1", "arg2"); // Output: Calling method 'nonExistentMethod' with arguments: arg1, arg2
__toString()
: This method is called when an object is treated as a string, such as in anecho
statement.
class MyClass {
public function __toString() {
return "This is my object.";
}
}
$object = new MyClass();
echo $object; // Output: This is my object.
__isset()
: This method is called when using the isset()
function to check if an inaccessible property exists.
class MyClass {
private $data = ['name' => 'John'];
public function __isset($name) {
return isset($this->data[$name]);
}
}
$object = new MyClass();
var_dump(isset($object->name)); // Output: bool(true)
var_dump(isset($object->age)); // Output: bool(false)
__unset()
: This method is called when using the unset()
function to unset an inaccessible property.
class MyClass {
private $data = ['name' => 'John'];
public function __unset($name) {
unset($this->data[$name]);
}
}
$object = new MyClass();
unset($object->name);
var_dump(isset($object->name)); // Output: bool(false)
__clone()
: This method is called when an object is cloned using the clone
keyword. It allows you to perform additional setup or modifications during cloning.
class MyClass {
public function __clone() {
echo "Object cloned.\n";
}
}
$object = new MyClass();
$clonedObject = clone $object; // Output: Object cloned.
__invoke()
: This method is called when an object is used as a function.
class MyClass {
public function __invoke($arg) {
echo "Invoked with argument: $arg\n";
}
}
$object = new MyClass();
$object("Hello"); // Output: Invoked with argument: Hello
__callStatic()
: This method is invoked when calling inaccessible static methods.
class MyClass {
public static function __callStatic($name, $arguments) {
echo "Calling static method '$name' with arguments: " . implode(', ', $arguments) . "\n";
}
}
MyClass::nonExistentStaticMethod("arg1", "arg2"); // Output: Calling static method 'nonExistentStaticMethod' with arguments: arg1, arg2
__serialize()
and __unserialize()
: These methods are invoked when an object is serialized and unserialized using serialize()
and unserialize()
. They allow you to control what data is serialized and how it's restored.
class MyClass {
private $data = 'Serialized Data';
public function __serialize(): array {
return ['data' => $this->data];
}
public function __unserialize(array $data): void {
$this->data = $data['data'];
}
}
$object = new MyClass();
$serialized = serialize($object);
$restoredObject = unserialize($serialized);
echo $restoredObject->data; // Output: Serialized Data
__sleep()
: This method is called first while executing serialize(). It returns the object’s property array on cleaning PHP class objects before serialization.
class Student { public $gender; public $name; public $reg; public function __construct($name ="", $reg = 25, $gender = 'Male') { $this->name = $name;
$this->reg = $reg;
$this->gender = $gender;
}
public function __sleep()
{
echo "It is called when the serialize() method is called outside the class.
";
$this->name = base64_encode($this->name);
return array('name', 'reg'); // It must return a value of which the elements are the name of the properties returned.
}
}
$obj = new Student('Ashok'); // Initially assigned.
echo serialize($obj);
__wakeup():
This method is called while deserialization() is executed. It would reverse work to restore objects properties and resources on invoking deserialization().
class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg = 30, $gender = 'Male') { $this->name = $name;
$this->reg =$reg;
$this->gender = $gender;
}
public function __sleep()
{
echo "It is called when the serialize() method is called outside the class.
";
$this->name = base64_encode($this->name);
return array('name', 'reg'); // It must return a value of which the elements are the name of the properties returned.
}
public function __wakeup()
{
echo "It is called when the unserialize() method is called outside the class.
";
$this->name = 2;
$this->gender = 'Male';
}
}
$obj= new Student('Peter'); // Initially assigned.
var_dump(serialize($obj));
var_dump(unserialize(serialize($obj)));
__set_state($array):
This method is called while calling var_export(). It is a static method invoked while exporting objects property array and expects such array variable as its argument.
class Student { public $gender; public $name; public $reg; public function __construct($name="", $reg=30, $gender='Male') { $this->name = $name;
$this->reg = $reg;
$this->gender = $gender;
}
}
$obj = new Student('Peter'); // Initially assigned.
var_export($obj);
__debugInfo():
This method is called by var_dump() while dumping an object to get the properties that should be shown. If the method is not defined on an object, then all public, protected and private properties will be shown.
class Sample { private $prop; public function __construct($val) { $this->prop = $val;
}
public function __debugInfo()
{
return [
'propSquared' => $this->prop ** 2,
];
}
}
var_dump(new Sample(22));
15. What are generators and how do you use them?
Generators in PHP are a special type of function that allows you to create iterators (sequences of values) without needing to load all values into memory at once. They enable you to generate values on-the-fly, which can be particularly useful when working with large data sets or dealing with streams.
Generators are declared using the yield
keyword within a function. Instead of using return
to provide a value, you use yield
to temporarily pause the execution of the function and yield the current value. Upon the next generator invocation, it resumes execution from where it was paused.
function generateNumbers($start, $end) {
for ($i = $start; $i <= $end; $i++) {
yield $i;
}
}
$numbers = generateNumbers(1, 5);
foreach ($numbers as $number) {
echo $number . ' ';
}
In this example, the generateNumbers
function is a generator that yields numbers from a given start-to-end value. During each iteration of the foreach
loop, the generator yields the next number without loading all the numbers into memory simultaneously. This allows for efficient handling of large data sets.
Generators are especially beneficial when dealing with data that can be generated or obtained in parts, as they reduce memory consumption and enable more efficient processing of large data volumes.