PHP OOP Classes & Objects

Classes, properties, methods and constructors.

✍️ 2 exercises in this lesson

Object-oriented PHP organises code into classes.

  • class Car { ... } defines a class; new Car() creates an object.
  • __construct() runs when an object is created. Constructor promotion (PHP 8) declares properties in the parameters.
  • $this refers to the current object; use -> to access members.
  • Visibility: public, protected, private.
  • static members belong to the class: Car::$count, self::.

Key Takeaways: PHP OOP Classes & Objects

Mastering PHP OOP Classes & Objects helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP OOP Classes & Objects Code Example

PHP
<?php
class BankAccount {
    private static int $count = 0;

    public function __construct(
        public string $owner,
        private float $balance = 0
    ) {
        self::$count++;
    }

    public function deposit(float $amount): static {
        $this->balance += $amount;
        return $this;
    }

    public function balance(): float { return $this->balance; }
    public static function count(): int { return self::$count; }
}

$acc = new BankAccount("Ayesha");
$acc->deposit(5000)->deposit(2500);
echo "{$acc->owner}: Rs {$acc->balance()}<br>";
echo "Accounts: " . BankAccount::count();
Output
Ayesha: Rs 7500
Accounts: 1
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP OOP Classes & Objects Practice Exercises

Check what you learned in “PHP OOP Classes & Objects”.

/ 2 solved
Fill in the blank

Create an object from the Car class.

$car =  Car("Toyota");
✓ Correct! Not quite. Try again.
Multiple choice

Which visibility allows access only inside the class?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services