SyntaxStudy
Sign Up
PHP Classes & Objects
PHP Beginner 6 min read

Classes & Objects

Object-Oriented Programming (OOP) organises code around objects — instances of classes that bundle data (properties) and behaviour (methods) together. A class is the blueprint; an object is the instance.

  • Define a class with the class keyword.
  • Create instances with new ClassName().
  • Access properties and methods with the -> arrow operator.
Example
<?php
class Product
{
    // Properties (typed since PHP 7.4)
    public string  $name;
    public float   $price;
    public 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 totalValue(): float
    {
        return $this->price * $this->stock;
    }

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

    public function describe(): string
    {
        return sprintf(
            '%s — $%.2f (%d in stock)',
            $this->name,
            $this->price,
            $this->stock
        );
    }
}

// Instantiate
$widget = new Product('Widget', 9.99, 50);
$gadget = new Product('Gadget', 49.99);

echo $widget->describe();       // Widget — $9.99 (50 in stock)
echo $widget->totalValue();     // 499.5
echo $gadget->isInStock() ? 'In stock' : 'Out of stock'; // Out of stock

// Multiple independent instances
$a = new Product('Alpha', 1.00, 10);
$b = new Product('Beta',  2.00, 5);
echo $a->name; // Alpha
echo $b->name; // Beta  — separate objects
Pro Tip

Tip: In PHP 8.0+ you can use constructor property promotion to declare and assign properties in one line: public function __construct(public string $name, public float $price) {} — no need to repeat the property declarations above the constructor.