23. PHP Classes and Objects

What you will learn

  • What classes and objects are
  • Properties, methods, and constructors
  • Visibility: public, private, protected
  • Inheritance, static members, and interfaces in brief

Why classes?

A class is a blueprint. An object is a thing built from that blueprint. A class bundles data (properties) with the actions (methods) that work on it. WordPress itself, and almost every modern PHP project, is built with classes.

A first class

PHP code

<?php
class Product
{
    public string $name;
    public float $price;

    public function describe(): string
    {
        return $this->name . " costs $" . number_format($this->price, 2);
    }
}

$pen = new Product();
$pen->name = "Pen";
$pen->price = 1.5;

$book = new Product();
$book->name = "Book";
$book->price = 12;

echo $pen->describe() . "<br>";
echo $book->describe();

What the browser shows

Pen costs $1.50
Book costs $12.00

  • new Product() creates an object. Each object has its own values.
  • -> reaches a property or method of an object.
  • Inside a method, $this means “the object I belong to”.

The constructor

The special method __construct() runs when an object is created, so you can set it up in one step. PHP 8 lets you declare the properties right in the parameter list.

PHP code

<?php
class Product
{
    public function __construct(
        public string $name,
        public float $price
    ) {
    }

    public function describe(): string
    {
        return $this->name . " costs $" . number_format($this->price, 2);
    }
}

$pen = new Product("Pen", 1.5);
echo $pen->describe();

Output

Pen costs $1.50

Promoted constructor properties like this need PHP 8.

Visibility: protecting data

Keyword Who can use it
public Anyone
protected The class and classes that extend it
private Only this class

Make properties private and offer methods to change them. The class can then refuse bad values.

PHP code

<?php
class Account
{
    private float $balance = 0;

    public function deposit(float $amount): void
    {
        if ($amount <= 0) {
            throw new InvalidArgumentException("Deposit must be positive.");
        }
        $this->balance += $amount;
    }

    public function balance(): float
    {
        return $this->balance;
    }
}

$account = new Account();
$account->deposit(50);
$account->deposit(25.5);

echo "Balance: " . $account->balance();

try {
    $account->deposit(-5);
} catch (InvalidArgumentException $e) {
    echo "<br>Error: " . $e->getMessage();
}

What the browser shows

Balance: 75.5
Error: Deposit must be positive.

Trying $account->balance = 1000000; from outside would fail, because the property is private. The only way in is through the checked method.

Inheritance

A class can extend another, gaining its properties and methods, and adding or changing some.

PHP code

<?php
class Animal
{
    public function __construct(protected string $name)
    {
    }

    public function speak(): string
    {
        return $this->name . " makes a sound.";
    }
}

class Dog extends Animal
{
    public function speak(): string
    {
        return $this->name . " says Woof!";
    }
}

$pets = [new Animal("Generic animal"), new Dog("Rex")];

foreach ($pets as $pet) {
    echo $pet->speak() . "<br>";
}

What the browser shows

Generic animal makes a sound.
Rex says Woof!

Dog replaces (overrides) speak(). Use parent::speak() to call the original too. Prefer small, simple hierarchies. Deep inheritance gets hard to follow.

Static members and constants

A static member belongs to the class itself, not to any object. Reach it with ::. A class constant is a fixed value.

PHP code

<?php
class Converter
{
    public const KM_PER_MILE = 1.609344;

    public static function milesToKm(float $miles): float
    {
        return $miles * self::KM_PER_MILE;
    }
}

echo round(Converter::milesToKm(10), 2) . " km";

Output

16.09 km

Interfaces in brief

An interface is a promise: any class that implements it must provide the listed methods. It lets different classes be used the same way.

PHP code

<?php
interface Shape
{
    public function area(): float;
}

class Square implements Shape
{
    public function __construct(private float $side) {}

    public function area(): float
    {
        return $this->side * $this->side;
    }
}

class Circle implements Shape
{
    public function __construct(private float $radius) {}

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

foreach ([new Square(3), new Circle(2)] as $shape) {
    echo round($shape->area(), 2) . "<br>";
}

What the browser shows

9
12.57

Loading classes from files

By convention each class lives in its own file, named after the class (Product.php), and is loaded with require_once. Larger projects use namespaces and an autoloader, such as the one provided by Composer, so classes load automatically.

Common mistakes

  • Forgetting $this-> inside a method, so PHP looks for a plain variable.
  • Using . instead of -> to reach a property. In PHP, . joins text.
  • Making every property public.
  • Forgetting new when creating an object.
  • Calling a non-static method as if it were static.
  • Building huge classes that do many unrelated jobs.

Exercise

Create a class Rectangle whose constructor takes a width and a height (both floats). Add a method area() that returns the area. Create a 6 by 4 rectangle and print its area.

Show solution
<?php
class Rectangle
{
    public function __construct(
        private float $width,
        private float $height
    ) {
    }

    public function area(): float
    {
        return $this->width * $this->height;
    }
}

$rect = new Rectangle(6, 4);
echo "Area: " . $rect->area();

The output is Area: 24.

Knowledge check

1. What is the difference between a class and an object?

A class is the blueprint. An object is one thing built from it.

2. What does $this refer to?

The object the method belongs to.

3. Why make a property private?

So the class controls how the data is changed, and can refuse bad values.

Summary

  • Classes bundle properties and methods, and objects are created with new.
  • Use constructors, private properties, and small focused classes.
  • Inheritance, static members, and interfaces help organise larger programs.
Scroll to Top