Lesson 10: Introduction to OOP

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects and classes. This lesson provides an introduction to OOP in PHP, focusing on classes, objects, constructors, and destructors.


10.1 Classes and Objects

What is a Class?

  • A class is a blueprint for creating objects. It defines the properties (attributes) and methods (functions) that an object can have.
  • Syntax:
    php
    class ClassName {
    // Properties
    public $property1;
    public $property2;
    // Methods
    public function method1() {
    // Code for the method
    }
    }

What is an Object?

  • An object is an instance of a class. It contains the data and methods defined by the class.
  • Creating an Object:
    php
    $object = new ClassName();

Example: Basic Class and Object

php
<?php
// Define a class
class Car {
public $make;
public $model;
public function displayDetails() {
echo “Car Make: “ . $this->make . “, Model: “ . $this->model . “<br>”;
}
}// Create an object of the class
$car1 = new Car();
$car1->make = “Toyota”;
$car1->model = “Corolla”;
$car1->displayDetails(); // Outputs: Car Make: Toyota, Model: Corolla

$car2 = new Car();
$car2->make = “Honda”;
$car2->model = “Civic”;
$car2->displayDetails(); // Outputs: Car Make: Honda, Model: Civic
?>

  • Key Concepts:
    • $this: Refers to the current object.
    • Properties: Variables inside a class.
    • Methods: Functions inside a class.

10.2 Access Modifiers

What are Access Modifiers?

Access modifiers define the visibility of class properties and methods.

Modifier Description
public Accessible from anywhere (default).
protected Accessible only within the class and subclasses.
private Accessible only within the class where it is defined.

Example: Access Modifiers

php
<?php
class Person {
public $name; // Accessible from anywhere
protected $age; // Accessible within the class and subclasses
private $salary; // Accessible only within the class
public function setDetails($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}public function displayDetails() {
echo “Name: $this->name, Age: $this->age<br>”;
}
}

$person = new Person();
$person->setDetails(“Alice”, 30, 50000);
$person->displayDetails(); // Outputs: Name: Alice, Age: 30
// echo $person->salary; // Error: Cannot access private property
?>


10.3 Constructors

What is a Constructor?

  • A constructor is a special method that automatically runs when an object is created.
  • Used to initialize properties or perform setup tasks.

Syntax

php
public function __construct(parameters) {
// Initialization code
}

Example: Using a Constructor

php
<?php
class Book {
public $title;
public $author;
// Constructor
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}public function displayDetails() {
echo “Title: $this->title, Author: $this->author<br>”;
}
}

// Create an object with constructor parameters
$book1 = new Book(“1984”, “George Orwell”);
$book1->displayDetails(); // Outputs: Title: 1984, Author: George Orwell

$book2 = new Book(“To Kill a Mockingbird”, “Harper Lee”);
$book2->displayDetails(); // Outputs: Title: To Kill a Mockingbird, Author: Harper Lee
?>


10.4 Destructors

What is a Destructor?

  • A destructor is a special method that is automatically called when an object is destroyed or goes out of scope.
  • Useful for cleanup tasks like closing database connections or releasing resources.

Syntax

php
public function __destruct() {
// Cleanup code
}

Example: Using a Destructor

php
<?php
class FileHandler {
private $filename;
// Constructor
public function __construct($filename) {
$this->filename = $filename;
echo “Opening file: $filename<br>”;
}// Destructor
public function __destruct() {
echo “Closing file: $this->filename<br>”;
}
}

// Create an object
$file = new FileHandler(“data.txt”);
// Destructor is automatically called when the script ends or object is no longer in use
?>

Output:

kotlin
Opening file: data.txt
Closing file: data.txt

Practical Example: Combining Concepts

Example: E-Commerce Product Class

php
<?php
class Product {
public $name;
private $price;
// Constructor
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}public function displayProduct() {
echo “Product: $this->name, Price: $this->price<br>”;
}

// Destructor
public function __destruct() {
echo “Removing product: $this->name<br>”;
}
}

$product1 = new Product(“Laptop”, 1500);
$product1->displayProduct();

$product2 = new Product(“Smartphone”, 800);
$product2->displayProduct();
?>


Activities and Exercises

  1. Classes and Objects:
    • Create a Car class with properties for make, model, and year. Add a method to display these details.
  2. Access Modifiers:
    • Modify the Car class to use protected for model and private for year. Add methods to get and set these properties.
  3. Constructors:
    • Create a Student class with properties for name and grade. Use a constructor to initialize these properties and display them using a method.
  4. Destructors:
    • Create a DatabaseConnection class that opens a connection in the constructor and closes it in the destructor.

Assignment

  1. Create a BankAccount class with:
    • Properties: accountNumber (public), balance (private).
    • Methods:
      • A constructor to initialize the account number and starting balance.
      • A method deposit($amount) to add funds.
      • A method withdraw($amount) to subtract funds if sufficient balance exists.
      • A method displayBalance() to show the current balance.
    • Implement access modifiers for security.
    • Use a destructor to print a message when the account object is destroyed.
  2. Test the class with multiple account objects and perform deposit/withdraw operations.

Summary

In this lesson, you learned:

  1. The basics of classes and objects in PHP.
  2. How to use access modifiers to control visibility.
  3. How constructors and destructors work to manage initialization and cleanup tasks.

These concepts are fundamental to creating reusable and scalable PHP applications. Let me know if you’d like more exercises or examples!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *