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
// Methodsclass ClassName {
// Properties
public $property1;
public $property2;
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
// 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
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
public function __construct(parameters) {
// Initialization code
}
Example: Using a Constructor
<?php
class Book {
public $title;
public $author;
// Constructorpublic 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
public function __destruct() {
// Cleanup code
}
Example: Using a Destructor
<?php
class FileHandler {
private $filename;
// Constructorpublic function __construct($filename) {
$this->filename = $filename;
echo “Opening file: $filename<br>”;
}
// Destructorpublic 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:
Opening file: data.txt
Closing file: data.txt
Practical Example: Combining Concepts
Example: E-Commerce Product Class
<?php
class Product {
public $name;
private $price;
// Constructorpublic 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
- Classes and Objects:
- Create a
Car
class with properties formake
,model
, andyear
. Add a method to display these details.
- Create a
- Access Modifiers:
- Modify the
Car
class to useprotected
formodel
andprivate
foryear
. Add methods to get and set these properties.
- Modify the
- Constructors:
- Create a
Student
class with properties forname
andgrade
. Use a constructor to initialize these properties and display them using a method.
- Create a
- Destructors:
- Create a
DatabaseConnection
class that opens a connection in the constructor and closes it in the destructor.
- Create a
Assignment
- 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.
- Properties:
- Test the class with multiple account objects and perform deposit/withdraw operations.
Summary
In this lesson, you learned:
- The basics of classes and objects in PHP.
- How to use access modifiers to control visibility.
- 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!
Leave a Reply