Mada za sehemu hiiCreating basic programs using classes and objectsMada 3
- Defining classes and creating objects
- Organising programs using constructors
- Constructing real-world models using classes and objects
Object-oriented programming (OOP)organises code by grouping related data and actions together into reusable units called objects. This approach makes programs easier to understand, maintain, and reuse because it mirrors how things work in the real world. In this topic, you will learn how to create classes (which are like blueprints or templates) and then use them to create actual objects that can store data and perform actions.
A class is a blueprint or template that defines the structure and behaviour of something. Think of it like an architect's plan for a house — the plan itself is not a house, but it describes what the house will look like and what it can do. In programming, a class describes the properties (what the object knows) and methods (what the object can do).
A class is defined using the class keyword, followed by the class name. In PHP, class names usually start with a capital letter. Here is a simple example of a class named Car:
class Car {
public $color; // a property
public function drive() { // a method
echo "The car is driving.";
}
}
In this example:
$coloris a property (also called an attribute) — it stores information about the cardrive()is a method — it defines an action the car can perform
An object is a real thing created from a class. If a class is the blueprint, then an object is the actual house built from that blueprint. You can create many objects from the same class, and each object will have its own separate data.
To create an object, you use the new keyword:
$myCar = new Car(); // Creates a new Car object
Now $myCar is an object of the class Car. It can access the property $color and the method drive() defined in the class.
Properties are variables that belong to a class. They describe the characteristics of an object. For example, a Student class might have properties like $name, $age, and $form.
Methods are functions inside a class that define the actions an object can perform. For example, a Dog class might have a bark() method:
class Dog {
public function bark() {
echo "Woof!";
}
}
To call a method on an object, you use the arrow operator ->:
$myDog = new Dog();
$myDog->bark(); // Outputs: Woof!
The new keyword is used to create a new object from a class. It works like telling a factory to build a new house from the architect's plan. When you use new, the program creates a new instance of that class in the computer's memory.
A constructor is a special method that runs automatically when an object is created. It is used to set initial values for the object's properties. In PHP (version 5 and later), the constructor is defined using the method name __construct().
Here is a Student class with a constructor:
class Student {
public $name;
public $age;
public $form;
// Constructor method - runs when object is created
public function __construct($studentName, $studentAge, $studentForm) {
$this->name = $studentName;
$this->age = $studentAge;
$this->form = $studentForm;
}
public function displayProfile() {
echo "Name: $this->name <br>";
echo "Age: $this->age <br>";
echo "Form: $this->form <br>";
}
}
The $this keyword refers to the current object. When you see $this->name, it means "the name property of this object."
Now you can create a student object and pass values to the constructor:
$student1 = new Student("Asha", 16, "Form Three");
$student1->displayProfile();
This will output:
Name: Asha
Age: 16
Form: Form Three
A destructor is a special method that is called automatically when an object is destroyed or goes out of scope. It is commonly used for cleanup tasks, such as releasing system resources. In PHP, the destructor is defined using __destruct().
class Student {
public $name;
public function __construct($studentName) {
$this->name = $studentName;
}
public function __destruct() {
echo "Object for $this->name is being destroyed.";
}
}
The destructor is called automatically when the script ends or when the object is no longer needed.
Let us look at a complete example that puts these concepts together. Imagine you need to create a simple bank account system. This is a real-world situation that can be modelled using classes and objects.
The BankAccount class should have:
- An owner name
- A balance (money in the account)
- Methods to deposit money, withdraw money, and check the balance
<?php
class BankAccount {
public $owner;
public $balance;
// Constructor to set up the account
public function __construct($accountOwner, $initialBalance) {
$this->owner = $accountOwner;
$this->balance = $initialBalance;
}
// Method to deposit money
public function deposit($amount) {
$this->balance += $amount;
echo "Deposited TZS $amount. New balance: TZS $this->balance <br>";
}
// Method to withdraw money
public function withdraw($amount) {
if ($amount > $this->balance) {
echo "Insufficient balance! <br>";
} else {
$this->balance -= $amount;
echo "Withdrew TZS $amount. Remaining balance: TZS $this->balance <br>";
}
}
// Method to check balance
public function checkBalance() {
echo "Account Balance for $this->owner: TZS $this->balance <br>";
}
}
// Creating an object
$myAccount = new BankAccount("Rehema", 10000);
$myAccount->deposit(2500);
$myAccount->withdraw(3000);
$myAccount->checkBalance();
?>
Output:
Deposited TZS 2500. New balance: TZS 12500
Withdrew TZS 3000. Remaining balance: TZS 9500
Account Balance for Rehema: TZS 9500
In this example:
- The
BankAccountclass is the blueprint $myAccountis an object (instance) of that class- The constructor sets the initial owner and balance
- The methods
deposit(),withdraw(), andcheckBalance()are actions the account can perform
- A class is a template or blueprint that defines properties and methods
- An object is a real thing created from a class using the
newkeyword - Properties describe what an object knows (its characteristics)
- Methods describe what an object can do (its actions)
- The constructor (
__construct) automatically runs when an object is created to initialise values - The destructor (
__destruct) automatically runs when an object is destroyed - The
$thiskeyword refers to the current object inside the class
In Tanzania, mobile money services like M-Pesa and Tigo Pesa use object-oriented programming principles similar to those learned in this topic. When you send money, the system treats each transaction as an object with properties (sender, receiver, amount, time) and methods (send, receive, check balance). This same class-and-object approach is used in school management systems to create student objects, each with their own name, form, and grades, making it easy for teachers to track and manage student information efficiently.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Define classes with appropriate attributes and methods.
- Use constructors to initialize objects.
- Create anduse objects effectively to perform tasks.
Tathmini ya matokeo
Classes are defined with logically structured attributes and methods, and objects are created.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Define classes and initialize attributes.
- Create and manipulate objects to perform specific tasks.
- Use methods within classes to implement functionality.
Principles: The student should explain the principle of:
- Object-oriented programming.
- The relationship between classes and objects in designing reusable code.
- Code organisation and reuse through object-oriented design.
Theories: The trainee should explain: The trainee should explain:
- How objects represent real-world entities in programming.
- The role of classes as blueprints for objects.
Circumstantial knowledge:
Detailed knowledge about:
- Common errors in defining and using classes and objects and how to resolve them.
- Best practices for naming classes, attributes, and methods.
Swali
What is a class in PHP object-oriented programming?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado