PHP Classes and Objects
# Chapter 20: PHP Classes and Objects
1. Introduction
Welcome to Chapter 20! In the previous chapter, we created basic objects and manually set their properties one by one. This is tedious. What if an object requires 10 properties to be set immediately upon creation? Furthermore, we made all our propertiespublic, meaning anyone could change them at any time. What if we want to restrict access to sensitive data like a user's password hash? In this chapter, we will master advanced OOP concepts: Constructors, Access Modifiers, $this, and the concept of Inheritance.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use the
$thiskeyword to reference the current object.
-
Automatically initialize data using the
__construct()method.
-
Secure data using Access Modifiers (
public,private,protected).
-
Share code between classes using Inheritance (
extends).
3. The $this Keyword
Inside a class method, the $this keyword refers to the *current object* that is calling the method. Because multiple objects can be created from the same class, PHP needs $this to know *which* object's properties to access.
4. The Constructor Method
A constructor is a magic method named__construct() (with two underscores). PHP automatically calls this function the exact moment an object is instantiated (new ClassName()). It is perfect for initializing properties automatically.
5. Access Modifiers (Encapsulation)
OOP is about control. Access Modifiers determine where properties and methods can be accessed.-
public: The property or method can be accessed from anywhere (inside and outside the class).
-
private: The property or method can ONLY be accessed from *inside* the class itself.
-
protected: Similar to private, but can also be accessed by classes that inherit it (we will cover inheritance next).
*Hiding data behind private properties and exposing them via controlled public methods (getters/setters) is a core OOP pillar called Encapsulation.*
6. Inheritance
What if you have aUser class, but you also want an Admin class that does everything a User does, but with extra features? Instead of rewriting code, the Admin class can inherit the properties and methods of the User class using the extends keyword.
7. Real-World Examples
Frameworks like Laravel use inheritance massively. You create aController class that extends BaseController. Your class automatically inherits routing and view-rendering functions written by the framework developers, saving you thousands of lines of code.
8. Output Explanations
In the BankAccount example, attempting to manually change the balance from the outside ($account->balance = 1000000;) will result in a fatal error because the property is private. The only way to interact with the balance is through the public methods the developer has explicitly provided (like getBalance()). This ensures the data remains valid and secure.
9. Common Mistakes
-
Forgetting the double underscores: Naming the constructor
construct()instead ofconstruct(). PHP will treat it as a normal method and it will not run automatically.
-
Trying to access private properties from a child class: A child class (using
extends) cannot accessprivateproperties of its parent. If you want the child to have access, but keep it hidden from the public outside, useprotected.
10. Best Practices
-
Make everything private by default. Only make properties
publicif you absolutely need them to be changed directly from outside the script. Use getter and setter methods to control data flow.
- Keep constructors lean. They should assign values, not perform heavy database queries.
11. Exercises
-
1.
Create a
Smartphoneclass with aconstruct()that accepts$brandand$model.
-
2.
Make a private property
$batteryleveland set it to 100 inside the constructor.
-
3.
Create a public method
getBattery()that returns the battery level.
12. Mini Project: Product Inventory System
Task: Build a ParentProduct class utilizing encapsulation and a constructor. Build a Child DigitalProduct class that inherits from it and adds a download link property.
13. Coding Challenges
Challenge 1: Modify theBankAccount class from section 5. Add a public method called deposit($amount). Inside the method, update the private balance ($this->balance += $amount;) and return the new balance. Test it.
14. MCQs with Answers
1. What is the name of the method that runs automatically when an object is instantiated? A)_init()
B) start()
C) construct()
D) build()
*Answer: C*
2. Which keyword allows a class to inherit from another class?
A) inherits
B) extends
C) implements
D) uses
*Answer: B*
3. Which access modifier completely hides a property from the outside and child classes? A) public B) protected C) static D) private *Answer: D*
15. Interview Questions
Q: Explain the concept of Encapsulation. *A:* Encapsulation is the OOP principle of hiding the internal state (properties) of an object and requiring all interaction to be performed through an object's methods. By making propertiesprivate and exposing public getters/setters, you prevent unauthorized or invalid manipulation of the object's data.
Q: What is the difference between private and protected?
*A:* A private property or method can only be accessed from within the exact class that defined it. A protected property or method is hidden from the outside world, but CAN be accessed by child classes that extend the parent class.
16. FAQs
Q: Can a class extend multiple parents? *A:* No, PHP does not support Multiple Inheritance (a class cannotextend two classes). However, PHP solves this using "Interfaces" and "Traits", which are advanced OOP concepts you will learn as you progress!
17. Summary
You are now writing highly professional, enterprise-grade code structures! You learned how to auto-initialize data using_construct(), reference the active object using $this, secure internal data via Encapsulation using private/protected access modifiers, and reuse vast amounts of code efficiently through Inheritance using extends.