PHP OOPs (Object-Oriented Programming) Interview Questions
This section focuses on object-oriented programming (OOP) concepts in PHP, including classes, objects, constructors, destructors, and namespaces.
PHP Sessions
A PHP session is a mechanism for storing user-specific data across multiple page requests within a web application. This data is stored on the server-side and is accessed using a unique session ID. Sessions are started using session_start()
, and data is stored in the $_SESSION
superglobal variable.
Constructors and Destructors in PHP
In PHP, a constructor is a special method (__construct()
) that's automatically called when an object of a class is created. It initializes the object's properties. Constructors can be overloaded (multiple constructors with different parameters). A destructor (__destruct()
) is called when an object is no longer needed; it's used for cleanup tasks (like releasing resources).
Why Developers Choose PHP
PHP's popularity stems from its ease of use, versatility, and large community support. Its extensive libraries and frameworks make web development efficient. Key features include:
- File handling (create, read, write, delete).
- Cookie management.
- Security features (access control).
- Data encryption.
Interfaces in PHP
An interface in PHP defines a contract specifying the methods a class must implement. This promotes code modularity and maintainability.
PHP Data Types
PHP supports various data types:
- String: Sequence of characters.
- Integer: Whole numbers.
- Double: Floating-point numbers.
- Boolean:
true
orfalse
. - Array: Ordered collection of values.
- Object: Instance of a class.
- NULL: Represents the absence of a value.
Object-Oriented Programming (OOP) in PHP
OOP is a programming paradigm organizing code around "objects" that encapsulate data and methods. Key OOP principles include:
- Encapsulation: Bundling data and methods that operate on that data within a class.
- Abstraction: Hiding implementation details and exposing only essential information.
- Inheritance: Creating new classes based on existing classes.
- Polymorphism: The ability of objects of different classes to respond to the same method call in their own specific way.
PHP supports OOP concepts through classes and objects.
Namespaces in PHP
Namespaces in PHP help organize code and prevent naming conflicts by grouping related classes, functions, and constants under a unique name. This is particularly helpful in larger projects.
echo
vs. print
in PHP
Function | echo |
print |
---|---|---|
Return Value | Void (no return value) | Returns 1 |
Arguments | Multiple arguments allowed | Single argument |
include()
vs. require()
Statement | include() |
require() |
---|---|---|
Error Handling | Issues a warning if the file cannot be included; script continues execution | Issues a fatal error if the file cannot be included; script stops |
Calling the Parent Constructor
Use parent::__construct()
to call the parent class's constructor from a child class's constructor. If the child class has its own constructor, you must call parent::__construct()
explicitly. If the child class does not have a constructor, the parent constructor will be called implicitly.
Implicit vs. Explicit Parent Constructor Calls
The parent class's constructor is called implicitly if the child class does not define its own constructor. It's called explicitly using parent::__construct()
when the child class has a constructor.
Object-Oriented Programming (OOP) Principles
[Provide a concise explanation of the four main pillars of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism.]
Classes in PHP
A class is a blueprint for creating objects. It defines the properties (variables) and methods (functions) of objects of that type.
Example
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce() {
return "My name is " . $this->name . ", and I am " . $this->age . " years old.";
}
}
Objects in PHP
An object is an instance of a class. It has specific values for the properties defined in the class.
Example
$person = new Person("Alice", 30);
echo $person->introduce();
Classes and Objects: Differences and Interrelation
Class | Object | |
---|---|---|
Definition | Blueprint or template | Instance of a class |
Properties | Defines properties | Has specific property values |
Methods | Defines methods | Can invoke methods |
Relationship | A class can have many objects | An object belongs to one class |
echo
and print
Both echo
and print
output data. echo
can take multiple arguments; print
takes one and returns 1.
include
and require
Both include external files. require
generates a fatal error if the file cannot be included; include
issues a warning and continues execution.
Classes and Objects in PHP
In PHP, a class is a blueprint for creating objects. It defines the properties (data) and methods (functions) that objects of that class will have. An object is an instance of a class; it's a concrete realization of that class's blueprint. Memory is allocated for an object's data when the object is created.
Example: Class Declaration
<?php
class MyClass {
public $name; // Property
public function myMethod() { // Method
// ...
}
}
?>
Example: Object Creation
<?php
$myObject = new MyClass();
?>
Constructors and Destructors
A constructor (__construct()
) is a special method that's automatically called when an object is created. It initializes the object's properties. A destructor (__destruct()
) is automatically called when an object is destroyed (no longer in use). It's used to perform any necessary cleanup tasks (like releasing resources).
Example
<?php
class MyClass {
public function __construct() {
echo "Object created!<br>";
}
public function __destruct() {
echo "Object destroyed!<br>";
}
}
?>
Member Variables and Member Functions
Member variables: Variables declared within a class. They hold the data associated with an object. Member functions (methods): Functions declared within a class. They define the behavior or actions that an object can perform. Member functions can access and modify the member variables of the same class.
Access Modifiers (Visibility)
Access modifiers control the visibility and accessibility of class members (variables and methods):
public
: Accessible from anywhere.protected
: Accessible within the class and its subclasses.private
: Accessible only within the class.
In PHP, members are public
by default unless otherwise specified.
Polymorphism
Polymorphism (meaning "many forms") is the ability of objects of different classes to respond to the same method call in their own specific ways. This is often achieved through inheritance and method overriding.
Classes in PHP
A class serves as a template or blueprint for creating objects. It defines the structure and behavior of those objects.
Example
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce() {
return "My name is " . $this->name . ", and I am " . $this->age . " years old.";
}
}
$person1 = new Person('Alice', 30);
echo $person1->introduce(); // Output: My name is Alice, and I am 30 years old.
?>
Objects in PHP
An object is a specific instance of a class. Each object has its own set of property values.
Example
<?php
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello, my name is " . $this->name;
}
}
$person1 = new Person('Bob');
echo $person1->greet(); // Output: Hello, my name is Bob.
$person2 = new Person('Charlie');
echo $person2->greet(); // Output: Hello, my name is Charlie.
?>
Classes and Objects: Relationship
A class is a blueprint; objects are created from that blueprint. A single class can have many objects, each with its own data.