Skip to main content
PHP for Beginners
CHAPTER 20 Beginner

PHP Classes and Objects

Updated: May 12, 2026
30 min read

# 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 properties public, 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 $this keyword 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.
php
12345678910
<?php
class User {
    public $name;

    public function printName() {
        // Echoes the 'name' property of the object calling this method
        echo "My name is " . $this->name;
    }
}
?>

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.
php
1234567891011121314151617
<?php
class Book {
    public $title;
    public $author;

    // This runs immediately upon creation
    public function __construct($book_title, $book_author) {
        $this->title = $book_title;
        $this->author = $book_author;
        echo "Book object created! <br>";
    }
}

// We pass the data directly into the parentheses!
$myBook = new Book("Harry Potter", "J.K. Rowling");
echo $myBook->title; // Outputs: Harry Potter
?>

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).
php
123456789101112131415161718192021
<?php
class BankAccount {
    public $account_holder;
    private $balance; // Hidden from the outside!

    public function __construct($name, $starting_balance) {
        $this->account_holder = $name;
        $this->balance = $starting_balance;
    }

    // A public method can access the private property internally
    public function getBalance() {
        return "Balance is: $" . $this->balance;
    }
}

$account = new BankAccount("John Doe", 500);
echo $account->account_holder; // OK!
// echo $account->balance; // FATAL ERROR: Cannot access private property
echo $account->getBalance(); // OK! Returns $500
?>

*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 a User 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.
php
1234567891011121314151617181920212223
<?php
// Parent Class
class User {
    public $username;
    
    public function login() {
        return $this->username . " logged in.";
    }
}

// Child Class inherits from User
class Admin extends User {
    public function deleteWebsite() {
        return "Website deleted by " . $this->username;
    }
}

$adminObj = new Admin();
$adminObj->username = "SuperBoss";
echo $adminObj->login(); // It has access to the parent's method!
echo "<br>";
echo $adminObj->deleteWebsite(); // And its own methods!
?>

7. Real-World Examples

Frameworks like Laravel use inheritance massively. You create a Controller 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 of construct(). 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 access private properties of its parent. If you want the child to have access, but keep it hidden from the public outside, use protected.

10. Best Practices

  • Make everything private by default. Only make properties public if 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. 1. Create a Smartphone class with a construct() that accepts $brand and $model.
  1. 2. Make a private property $batterylevel and set it to 100 inside the constructor.
  1. 3. Create a public method getBattery() that returns the battery level.

12. Mini Project: Product Inventory System

Task: Build a Parent Product class utilizing encapsulation and a constructor. Build a Child DigitalProduct class that inherits from it and adds a download link property.
php
12345678910111213141516171819202122232425262728293031323334353637383940414243
<?php
class Product {
    protected $name;
    protected $price;

    public function __construct($name, $price) {
        $this->name = $name;
        $this->price = $price;
    }

    public function getDetails() {
        return "Product: {$this->name} | Price: $" . number_format($this->price, 2);
    }
}

class DigitalProduct extends Product {
    private $download_link;

    // Overriding the constructor to add link
    public function __construct($name, $price, $link) {
        parent::__construct($name, $price); // Call the parent's constructor!
        $this->download_link = $link;
    }

    // Adding a new method
    public function getLink() {
        return "Download here: " . $this->download_link;
    }
}

$ebook = new DigitalProduct("PHP Mastery E-Book", 19.99, "https://example.com/dl/php");
?>

<!DOCTYPE html>
<html>
<body>
    <h2>Store Inventory</h2>
    <div style="border: 1px solid black; padding: 15px; width: 300px;">
        <p><strong><?php echo $ebook->getDetails(); ?></strong></p>
        <a href="<?php echo $ebook->getLink(); ?>">Download File</a>
    </div>
</body>
</html>

13. Coding Challenges

Challenge 1: Modify the BankAccount 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 properties private 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 cannot extend 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.

18. Next Chapter Recommendation

Our PHP scripts are now highly structured, but they still don't have permanent, scalable data storage. Text files aren't enough. In Chapter 21: PHP MySQL Database Connection, we will finally introduce databases and connect our PHP application to MySQL!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·