Sonzaschool
Rudi

Sekondari ya Kawaida · Kidato cha Tatu · Amali · Electronics and Computer

Computer Programming

Organising programs using constructors

takriban dakika 3 kusoma

Majadiliano
Mada za sehemu hiiCreating basic programs using classes and objectsMada 3

A constructor is a special method inside a class that runs automatically when you create a new object. Its primary purpose is to initialise the object's properties with starting values, ensuring the object is ready to use immediately after it is created.

Key Features of Constructors

  • Automatic Execution: The constructor is called automatically when an object is created using the new keyword; you do not need to call it separately.
  • Used for Initialisation: It sets up initial values for an object's properties.
  • Only One Constructor: A class generally has one constructor method.
  • No Return Value: A constructor does not return any value, not even void.

Defining a Constructor in PHP

In PHP 5 and later, constructors are defined using the method name __construct().

class Student {
    public $name;
    public $form;

    // This is the constructor method
    public function __construct($studentName, $studentForm) {
        $this->name = $studentName;
        $this->form = $studentForm;
    }

    public function introduce() {
        echo "My name is $this->name and I am in Form $this->form.";
    }
}

The keyword $this refers to the current object. $this->name means "the name property of this object."

Using the Constructor

When creating an object, you pass the initial values as arguments to the class:

$student1 = new Student("Amina", "Three");
$student1->introduce();
// Output: My name is Amina and I am in Form Three.

Worked Example: Bank Account

Consider a BankAccount class. When a new account is opened, the system must immediately know who owns the account and what the starting balance is. The constructor handles this automatically.

<?php
class BankAccount {
    public $owner;
    public $balance;

    // Constructor to set initial values
    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>";
    }
}

// Creating an object using the constructor
$myAccount = new BankAccount("Rehema", 10000);
$myAccount->deposit(5000);
?>

In this example, new BankAccount("Rehema", 10000) creates the object and runs the constructor immediately, setting the owner to "Rehema" and balance to 10,000.

Brief Note on Destructors

A destructor (__destruct()) is the opposite of a constructor. It is automatically called when an object is destroyed or goes out of scope (for example, when the script ends). It is commonly used for cleanup tasks, such as closing a file or releasing a resource.

Real-life application

In Tanzanian mobile money systems like M-Pesa, constructors are used when a new subscriber registers. For instance, when you sign up, the system creates a user object and uses a constructor to automatically set your phone number and initial balance to zero, making the account ready for deposits and withdrawals immediately.

Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa

Tathmini ya mchakato

The student should be able to: 87

  • Define constructors with proper syntax and initialise attributes.
  • Use constructors to create and initialise objects dynamically.
  • Incorporate constructors effectively in organizing class functionality

Tathmini ya matokeo

Constructors are correctly implemented and used to initialise objects to meet problem requirements and adhere to object-oriented principles.

Tathmini ya maarifa

Methods used: The trainee should explain how to:

  • Define constructors in classes with and without parameters.
  • Use constructor overloading to handle multiple initialisation scenarios.
  • Incorporate constructors in program design for object creation.

Principles: The student should explain the principle of:

  • Object initialization using constructors.

Theories: The trainee should explain: The trainee should explain:

  • The role of constructors in managing object states.
  • The advantages of using constructors over direct attribute assignment.

Circumstantial knowledge:

Detailed knowledge about:

  • Common errors in constructor implementation and how to resolve them.
  • Best practices for designing and organizing constructors in classes.

Swali

What is the primary purpose of a constructor in object-oriented programming?

Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.

Ingia ili kufanya mazoezi

Mwalimu

Umekwama? Niulize chochote kuhusu mada hii.

Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.

Ingia ili kuuliza

Majadiliano

Hakuna maswali bado

Ingia ili kuuliza
Inapakia majadiliano…