Object-Oriented Programming in PHP
Master Object-Oriented Programming in PHP, including classes, inheritance, polymorphism, encapsulation, interfaces, and design patterns.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is OOP and what are its four pillars in PHP?
Short Answer
On the web, you can mix visual styles by applying different CSS font-family rules to inline HTML elements like <span>. You would use a cursive web font (like from Google Fonts) for the "handwritten" text, and a standard sans-serif/serif font for the normal text.
Code Example
1. Import a cursive font:
<link href="https://fonts.googleapis.com/css2?family=Caveat&display=swap" rel="stylesheet">
2. Create the CSS and HTML:
<style>
.normal-text {
font-family: 'Arial', sans-serif;
font-size: 16px;
}
.handwriting {
font-family: 'Caveat', cursive;
font-size: 24px;
color: blue; /* Looks like pen ink */
}
</style>
<p class="normal-text">
Please sign here: <span class="handwriting">Prepiq User</span>
</p>
Q2. What is the difference between a class and an object in PHP?
A class is a blueprint or template that defines properties and methods. An object is a concrete instance created from that blueprint, with its own actual values in memory.
class Car {
public string $color;
public function drive() { return $this->color . ' car is driving'; }
}
$car1 = new Car();
$car1->color = 'Red';
$car2 = new Car();
$car2->color = 'Blue';| Aspect | Class | Object |
|---|---|---|
| Nature | Blueprint/template, no memory allocated for data | Actual instance with allocated memory |
| Count | One class definition | Many objects can be created from one class |
| Keyword | class | new |
Interview tip: Use the analogy: class is the architectural blueprint of a house, an object is an actual house built from it - many houses (objects), one blueprint (class).
Q3. Explain encapsulation in PHP with an example.
Short Answer
Both echo and print are language constructs used to output data to the screen. The main differences are that echo can take multiple parameters and has no return value, making it marginally faster. print can only take a single argument and always returns 1, meaning it can be used in expressions.
Comparison Table
| Feature | echo |
print |
|---|---|---|
| Return Value | None (void) | Returns 1 |
| Multiple Arguments | Supported (e.g., echo "a", "b";) |
Not Supported |
| Speed | Slightly faster | Slightly slower |
| Usage in Expressions | No | Yes (e.g., $val = print("Hi");) |
Code Example
// echo multiple strings
echo "Hello ", "World", "!";
// print returning a value (useful in ternary operators)
$isPrinted = print("Hello World!"); // Outputs: Hello World!
echo $isPrinted; // Outputs: 1
// echo inside an expression will cause a Syntax Error
// $val = (echo "test"); // ERROR!
Interview Tip
In modern PHP development, always use echo. The speed difference is microscopic, but echo is the universally accepted standard in the PHP community.
Q4. Explain inheritance in PHP with an example.
Short Answer
PHP supports 8 primitive data types categorized into scalar, compound, and special types. These include String, Integer, Float, Boolean (Scalar), Array, Object (Compound), and NULL, Resource (Special).
Code Example: Common Data Types
Since PHP is a loosely typed language, you do not need to explicitly declare data types when creating variables. PHP automatically converts the variable to the correct data type based on its value.
// Scalar Types
$name = "Prepiq"; // String
$age = 25; // Integer
$price = 19.99; // Float (Double)
$isActive = true; // Boolean
// Compound Types
$colors = ["Red", "Blue", "Green"]; // Array
$user = new stdClass(); // Object
// Special Types
$connection = null; // NULL
// $file = fopen("test.txt", "r"); // Resource
Important Points
- Loosely Typed: You can change a variable from an integer to a string simply by reassigning it.
- Type Juggling: PHP will automatically attempt to convert types during comparisons (e.g.,
"1" == 1is true). This is why using strict comparison (===) is recommended.
Q5. Explain polymorphism in PHP with an example.
Short Answer
== (Equal) checks if two values are equal after performing "type juggling" (converting them to the same data type).
=== (Identical / Strict Equal) checks if two values are equal AND are of the exact same data type. It does NOT convert types.
Detailed Explanation & Code Example
In PHP, type juggling can lead to dangerous, unexpected bugs. It is a best practice to almost always use strict comparison (===).
$a = 5; // Integer
$b = "5"; // String
// Loose Comparison (==)
if ($a == $b) {
echo "True! PHP converted the string '5' to an integer for comparison.";
}
// Strict Comparison (===)
if ($a === $b) {
echo "This will NOT execute.";
} else {
echo "False! They look the same, but one is an Integer and one is a String.";
}
Common Pitfall Example
Consider the strpos() function, which returns the numeric index of a substring, or false if it's not found.
$str = "Hello World";
$position = strpos($str, "Hello"); // Returns 0 (index 0)
// BAD CODE: 0 == false is TRUE in loose comparison!
if ($position == false) {
echo "Not found!"; // This incorrectly executes because 0 == false
}
// GOOD CODE: 0 !== false in strict comparison.
if ($position === false) {
echo "Not found!";
}
Q6. What is abstraction in PHP and how does it differ from encapsulation?
Short Answer
Variable scope defines where a variable can be accessed or modified within a script. PHP has three main scopes: Local (inside a function), Global (outside a function), and Static (persists data across function calls).
Detailed Explanation & Examples
1. Local Scope
Variables declared inside a function are local to that function. They cannot be accessed from outside.
function testLocal() {
$age = 25; // Local scope
echo $age;
}
testLocal(); // Outputs: 25
// echo $age; // Error: Undefined variable
2. Global Scope
Variables declared outside of any function have global scope. By default, they cannot be accessed inside a function unless you use the global keyword.
$name = "Prepiq"; // Global scope
function testGlobal() {
global $name; // Import the global variable
echo $name;
}
testGlobal(); // Outputs: Prepiq
3. Static Scope
Normally, when a function finishes executing, all of its local variables are deleted. A static variable is NOT deleted. It remembers its value from the previous time the function was called.
function counter() {
static $count = 0; // Only initialized once
$count++;
echo $count . " ";
}
counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3
Q7. What are access modifiers in PHP (public, protected, private)?
Short Answer
A superglobal is a built-in array variable in PHP that is accessible from anywhere in your script—inside functions, classes, or loops—without needing to use the global keyword.
Detailed Explanation
In PHP, normal variables have a restricted scope. If you define a variable outside a function, you cannot access it inside a function unless you pass it as a parameter or use the global keyword. Superglobals bypass this rule.
The primary PHP superglobals are:
$_GET: Variables passed via URL parameters.$_POST: Variables passed via HTTP POST (like form submissions).$_SESSION: Session variables stored on the server.$_COOKIE: Cookie variables sent by the client browser.$_SERVER: Server and execution environment information (e.g., headers, paths, script locations).$_REQUEST: Combines GET, POST, and COOKIE data.$_FILES: Data related to uploaded files via HTTP POST.
Code Example
// Even though this is inside a function, we can access $_SERVER without any extra code
function printUserIP() {
echo "Your IP is: " . $_SERVER['REMOTE_ADDR'];
}
printUserIP();
Q8. What is method overriding in PHP? Does PHP support method overloading?
Short Answer
These functions are used to import code from another file into your current script.
include emits a Warning if the file is missing, but continues script execution.
require emits a Fatal Error if the file is missing, and halts script execution immediately.
The _once suffix (include_once / require_once) tells PHP to check if the file was already included previously, and if so, it will not include it a second time (preventing "Cannot redeclare" errors).
Detailed Explanation & Code Example
When building applications, you often separate code into multiple files (e.g., configuration, header, footer).
// If header.php is missing, a warning is shown, but "Page content" is still echoed.
include 'header.php';
echo "Page content";
// If database.php is missing, execution stops completely.
require 'database.php';
echo "Database connected";
Interview Tip
Use require for critical files (like database connections) where the app shouldn't run if the file is missing. Use include for non-critical files (like an optional sidebar).
Q9. What are traits in PHP and why are they used?
Short Answer
GET and POST are the two primary HTTP methods used to send data from a client (like a web browser) to a server (PHP). GET appends data to the URL string, making it visible and bookmarkable. POST sends data silently in the HTTP request body, making it suitable for sensitive or large amounts of data.
Comparison Table
| Feature | GET | POST |
|---|---|---|
| Visibility | Visible in the URL (e.g., ?name=prepiq) |
Hidden in the HTTP body |
| Security | Low (never use for passwords) | Higher (safe for passwords/tokens) |
| Size Limit | Limited by URL max length (approx. 2048 chars) | Virtually unlimited |
| Idempotency | Idempotent (safe to refresh/bookmark) | Not idempotent (refreshing resubmits data) |
When to use which?
- Use GET for: Search queries, filtering, sorting, or retrieving data where the state of the database is not modified. GET requests are easily cacheable by browsers and CDNs.
- Use POST for: Logging in, submitting forms, uploading files, or performing any action that changes data in the database (Create, Update, Delete).
Q10. What are magic methods in PHP? Explain __get, __set, __call, and __toString.
Magic methods are special methods prefixed with double underscores that PHP calls automatically in specific situations, without you calling them directly.
| Method | Triggered when |
|---|---|
| __get($name) | Reading an inaccessible or undefined property |
| __set($name, $value) | Writing to an inaccessible or undefined property |
| __call($name, $args) | Calling an inaccessible or undefined method |
| __toString() | Object is used in a string context, e.g. echo $obj |
| __invoke() | Object is called like a function, e.g. $obj() |
class Product {
private array $data = [];
public function __set($name, $value) { $this->data[$name] = $value; }
public function __get($name) { return $this->data[$name] ?? null; }
public function __toString(): string { return 'Product: ' . ($this->data['name'] ?? 'Unknown'); }
}
$p = new Product();
$p->name = 'Laptop'; // triggers __set
echo $p->name; // triggers __get
echo $p; // triggers __toStringInterview tip: Warn that overusing magic methods hurts IDE autocompletion and debuggability - use them for specific patterns like ORMs or DTOs, not as a default habit.
Object-Oriented Programming in PHP
Master Object-Oriented Programming in PHP, including classes, inheritance, polymorphism, encapsulation, interfaces, and design patterns.
What is OOP and what are its four pillars in PHP?
Short Answer On the web, you can mix visual styles by applying different CSS font-family rules to inline HTML...
What is the difference between a class and an object in PHP?
A class is a blueprint or template that defines properties and methods. An object is a concrete instance creat...
Explain encapsulation in PHP with an example.
Short Answer Both echo and print are language constructs used to output data to the screen. The main differenc...
Explain inheritance in PHP with an example.
Short Answer PHP supports 8 primitive data types categorized into scalar, compound, and special types. These i...
Explain polymorphism in PHP with an example.
Short Answer == (Equal) checks if two values are equal after performing "type juggling" (converting them to th...
What is abstraction in PHP and how does it differ from encapsulation?
Short Answer Variable scope defines where a variable can be accessed or modified within a script. PHP has thre...
What are access modifiers in PHP (public, protected, private)?
Short Answer A superglobal is a built-in array variable in PHP that is accessible from anywhere in your script...
What is method overriding in PHP? Does PHP support method overloading?
Short Answer These functions are used to import code from another file into your current script. include emit...
What are traits in PHP and why are they used?
Short Answer GET and POST are the two primary HTTP methods used to send data from a client (like a web browser...
What are magic methods in PHP? Explain __get, __set, __call, and __toString.
Magic methods are special methods prefixed with double underscores that PHP calls automatically in specific si...