PHP Fundamentals

Classes & Objects Basics

13 min Lesson 21 of 45

Introduction to Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects rather than functions and logic. It helps you write more maintainable, reusable, and scalable code.

Key OOP Concepts:
  • Class: A blueprint or template for creating objects
  • Object: An instance of a class with specific values
  • Property: Variables that belong to a class
  • Method: Functions that belong to a class

Creating Your First Class

A class is defined using the class keyword. Let's create a simple User class:

<?php class User { // Properties (attributes) public $name; public $email; public $age; // Method (function) public function introduce() { return "Hi, I'm " . $this->name . " and I'm " . $this->age . " years old."; } public function isAdult() { return $this->age >= 18; } } ?>
Tip: The $this keyword refers to the current object instance. Use it to access properties and methods within the class.

Creating Objects (Instantiation)

Once you have a class, you can create objects from it using the new keyword:

<?php // Create a new User object $user1 = new User(); $user1->name = "Ahmed"; $user1->email = "ahmed@example.com"; $user1->age = 25; echo $user1->introduce(); // Output: Hi, I'm Ahmed and I'm 25 years old. echo $user1->isAdult() ? "Adult" : "Minor"; // Output: Adult // Create another User object $user2 = new User(); $user2->name = "Sara"; $user2->email = "sara@example.com"; $user2->age = 16; echo $user2->introduce(); // Output: Hi, I'm Sara and I'm 16 years old. ?>

Constructor Method

A constructor is a special method that runs automatically when an object is created. It's perfect for initializing properties:

<?php class User { public $name; public $email; public $age; // Constructor public function __construct($name, $email, $age) { $this->name = $name; $this->email = $email; $this->age = $age; } public function introduce() { return "Hi, I'm {$this->name} and I'm {$this->age} years old."; } } // Now we can create objects in one line $user1 = new User("Ahmed", "ahmed@example.com", 25); $user2 = new User("Sara", "sara@example.com", 16); echo $user1->introduce(); ?>
Constructor Naming: In PHP, constructors are named __construct() (with two underscores). This is called a "magic method."

Practical Example: Product Class

Let's create a more practical example for an e-commerce system:

<?php class Product { public $name; public $price; public $quantity; public $category; public function __construct($name, $price, $quantity, $category) { $this->name = $name; $this->price = $price; $this->quantity = $quantity; $this->category = $category; } // Calculate total value public function getTotalValue() { return $this->price * $this->quantity; } // Check if in stock public function isInStock() { return $this->quantity > 0; } // Apply discount public function applyDiscount($percentage) { $discount = $this->price * ($percentage / 100); $this->price -= $discount; return "Discount of {$percentage}% applied. New price: $" . $this->price; } // Display product info public function displayInfo() { $status = $this->isInStock() ? "In Stock" : "Out of Stock"; return " <div class='product'> <h3>{$this->name}</h3> <p>Price: \${$this->price}</p> <p>Quantity: {$this->quantity}</p> <p>Category: {$this->category}</p> <p>Status: {$status}</p> <p>Total Value: \$" . $this->getTotalValue() . "</p> </div> "; } } // Create products $laptop = new Product("Dell XPS 13", 999, 5, "Electronics"); $book = new Product("PHP Programming", 29.99, 0, "Books"); echo $laptop->displayInfo(); echo $laptop->applyDiscount(10); // 10% discount echo $book->displayInfo(); ?>

The $this Keyword Explained

The $this keyword is crucial in OOP. It refers to the current object:

<?php class Counter { public $count = 0; public function increment() { $this->count++; // Access property of current object return $this->count; } public function decrement() { $this->count--; return $this->count; } public function reset() { $this->count = 0; return $this; // Return current object for method chaining } } $counter1 = new Counter(); $counter2 = new Counter(); $counter1->increment(); // $counter1->count = 1 $counter1->increment(); // $counter1->count = 2 $counter2->increment(); // $counter2->count = 1 echo $counter1->count; // Output: 2 echo $counter2->count; // Output: 1 ?>
Method Chaining: By returning $this from a method, you can chain multiple method calls: $obj->method1()->method2()->method3()

Type Declarations (Type Hints)

PHP allows you to specify data types for parameters and return values:

<?php class Calculator { // Type hints for parameters and return value public function add(int $a, int $b): int { return $a + $b; } public function divide(float $a, float $b): float { if ($b == 0) { throw new Exception("Division by zero"); } return $a / $b; } public function multiply(int|float $a, int|float $b): int|float { return $a * $b; // PHP 8+ union types } } $calc = new Calculator(); echo $calc->add(5, 3); // Output: 8 echo $calc->divide(10.5, 2); // Output: 5.25 echo $calc->multiply(4, 2.5); // Output: 10 ?>

Checking Object Type

You can check if an object is an instance of a class:

<?php class User { public $name; } class Product { public $name; } $user = new User(); $product = new Product(); // Check object type if ($user instanceof User) { echo "This is a User object"; } if ($product instanceof Product) { echo "This is a Product object"; } // Get class name echo get_class($user); // Output: User ?>
Exercise:

Create a BankAccount class with the following features:

  • Properties: accountNumber, accountHolder, balance
  • Constructor that initializes all properties (balance defaults to 0)
  • Method deposit($amount) that adds to balance
  • Method withdraw($amount) that subtracts from balance (check sufficient funds)
  • Method getBalance() that returns current balance
  • Method displayStatement() that shows account info

Create two accounts and test all methods.

Best Practices

  • Naming: Use PascalCase for class names (UserProfile, ProductManager)
  • Single Responsibility: Each class should have one clear purpose
  • Meaningful Names: Use descriptive names for properties and methods
  • Consistency: Follow consistent naming and coding conventions
  • Documentation: Add comments to explain complex logic

Common Mistakes to Avoid

Watch out for these common errors:
  • Forgetting $this: Always use $this-> to access properties/methods
  • Missing new keyword: Must use new to create objects
  • Wrong arrow operator: Use -> for objects, not ::
  • Undefined properties: Initialize properties before using them

Summary

In this lesson, you learned:

  • What classes and objects are in PHP
  • How to create classes with properties and methods
  • How to instantiate objects using the new keyword
  • How to use constructors to initialize objects
  • How to use the $this keyword
  • Type declarations for better code safety
  • Best practices for object-oriented PHP

Next, we'll learn about access modifiers and encapsulation to make our code more secure and maintainable!