phpPHP
Module 14: Object-Oriented PHPIntermediate55 min read

Object-Oriented PHP: Classes, Encapsulation, Constructors & Object Lifecycle

Master PHP OOP fundamentals: classes vs objects, encapsulation, public/protected/private, __construct/__destruct, $this, static members, and __clone.

Key Takeaways & Core Concepts
  • `$this`: Refers to the current object instance.
  • `static` members: Belong to the class itself (self::$count), not individual instances.
  • Object Cloning: $b = clone $a; performs a shallow copy; implement __clone() for deep copies of nested objects.

Object-Oriented PHP: Classes, Encapsulation, Constructors & Object Lifecycle

### 1. Procedural vs. OOP & Encapsulation OOP models domain entities with state (properties) and behavior (methods), enforcing invariants via private / protected / public visibility.

  • `$this`: Refers to the current object instance.
  • `static` members: Belong to the class itself (self::$count), not individual instances.
  • Object Cloning: $b = clone $a; performs a shallow copy; implement __clone() for deep copies of nested objects.
1. Encapsulated BankAccount with Constructor & Static Counter
1<?php
2declare(strict_types=1);
3
4class BankAccount {
5 private static int $accounts = 0;
6 public function __construct(private string $owner, private float $balance) {
7 self::$accounts++;
8 }
9 public function deposit(float $amt): void {
10 if ($amt > 0) $this->balance += $amt;
11 }
12 public function getBalance(): float { return $this->balance; }
13 public static function count(): int { return self::$accounts; }
14}
15
16$acc = new BankAccount("Aarav", 1000.0);
17$acc->deposit(500.0);
18echo "Balance: " . $acc->getBalance() . " | Accounts: " . BankAccount::count() . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
18 lines
Note: Uses PHP 8.0 constructor property promotion with private encapsulation.
Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)