PG 6
PG 6
Suggested Solution: The four main principles of OOP are encapsulation, inheritance,
polymorphism, and abstraction.
2. Understanding
Question: Can you explain how encapsulation works in PHP and why it is important?
Suggested Solution: Encapsulation in PHP involves bundling data (properties) and methods
within a class while restricting direct access to some of its components. It is important because it
helps protect the integrity of the data by preventing unintended interference and modification,
promoting better code organization.
3. Applying
Question: How would you implement encapsulation in a PHP class that represents a user
profile?
Suggested Solution: You can create a UserProfile class with private properties for user data
(e.g., username, password) and public methods for setting and getting those properties. This way,
you control how the properties can be accessed or modified.
php
Copy code
class UserProfile {
private $username;
private $password;
4. Analyzing
Question: Compare and contrast inheritance and polymorphism in PHP.
Suggested Solution: Inheritance allows a class to inherit properties and methods from another
class, enabling code reuse and establishing a hierarchical relationship. Polymorphism, on the
other hand, allows methods to perform different functions based on the object that is calling
them. While inheritance is about "is-a" relationships, polymorphism allows for "one interface,
multiple implementations."
5. Evaluating
Question: Evaluate the advantages and disadvantages of using abstract classes versus interfaces
in PHP.
Suggested Solution:
6. Creating
Question: Design a simple class hierarchy in PHP that illustrates the use of inheritance, and
create an instance that utilizes polymorphism.
Suggested Solution: You could create a Shape class with an area() method, and subclasses like
Circle and Square that implement the area() method differently. For example:
php
Copy code
abstract class Shape {
abstract public function area();
}
// Polymorphism in action
$shapes = [new Circle(5), new Square(4)];