📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners OOP — Classes and Objects

OOP — Classes and Objects

6 min read Quiz at the end
OOP organizes code into classes and objects. A class is a blueprint and an object is an instance of it. Properties store data, methods define behaviour, and access modifiers (public, private, protected) control visibility.

Classes and Objects

class Product {
    // Properties
    public string $name;
    protected float $price;
    private int $stock;

    // Constructor
    public function __construct(
        string $name,
        float $price,
        int $stock = 0
    ) {
        $this->name  = $name;
        $this->price = $price;
        $this->stock = $stock;
    }

    // Method
    public function getPrice(): float {
        return $this->price;
    }

    public function isAvailable(): bool {
        return $this->stock > 0;
    }
}

$p = new Product("Laptop", 999.99, 10);
echo $p->name;           // Laptop
echo $p->getPrice();     // 999.99
echo $p->isAvailable();  // true
Topic Quiz · 5 questions

Test your understanding before moving on

1. What does public mean on a property?
💡 public properties and methods are accessible from anywhere.
2. What does protected mean?
💡 protected is accessible within the class and any subclasses.
3. What does private mean?
💡 private members are only accessible inside the class that defines them.
4. What does $this refer to inside a class?
💡 $this refers to the current object instance inside a method.
5. Which method is called when creating a new object?
💡 __construct() is the constructor — called automatically when new ClassName() is used.