PHP Tutorial menu

PHP Classes and Objects

Object-oriented programming (OOP) groups data and the code that works on it into one unit called a class.

Class and Object

  • A class is a plan or template, like the design of a car
  • An object is a real thing made from that plan, like one actual car
  • Properties are the data of an object (colour, model)
  • Methods are functions inside a class (start, stop)

Your First Class

Example

php
<?php
class Student {
    public string $name;
    public int $marks;

    public function result(): string {
        return $this->marks >= 40 ? "Pass" : "Fail";
    }
}

$s = new Student();
$s->name = "Ali";
$s->marks = 68;

echo $s->name . ": " . $s->result();
Output
Ali: Pass
  • new Student() creates an object
  • -> reaches a property or method of an object
  • $this means "this object" inside the class

Constructors

A constructor runs automatically when you create the object. It is the place to set starting values.

Example

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

    public function label(): string {
        return "{$this->name} - Rs " . number_format($this->price);
    }
}

$fan = new Product("Ceiling Fan", 8500, 12);
echo $fan->label() . "<br>";
echo "In stock: " . $fan->stock;
Output
Ceiling Fan - Rs 8,500
In stock: 12

Writing public before the constructor parameters is called constructor promotion (PHP 8). It creates and fills the properties in one step.

Visibility

KeywordWho can use the property or method
publicEveryone
protectedThe class and its child classes
privateOnly the class itself

Keep data private and give methods to change it safely:

Example

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

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

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

$acc = new BankAccount();
$acc->deposit(5000);
$acc->deposit(2500);
echo "Balance: Rs " . $acc->getBalance();
Output
Balance: Rs 7500

Writing $acc->balance = 1000000; from outside would give an error, because the property is private.

Inheritance

A child class gets everything from its parent class and can add or change things. Use extends:

Example

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

    public function introduce(): string {
        return "I am {$this->name}.";
    }
}

class Teacher extends Person {
    public function __construct(string $name, private string $subject) {
        parent::__construct($name);
    }

    public function introduce(): string {
        return parent::introduce() . " I teach {$this->subject}.";
    }
}

$t = new Teacher("Sir Imran", "PHP");
echo $t->introduce();
Output
I am Sir Imran. I teach PHP.

Frameworks like Laravel and WordPress plugins use classes everywhere. Understanding OOP makes them much easier to learn.

Exercise

Exercise

Which keyword makes a property usable only inside its own class?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp