Sonzaschool
Back

O-Level · Form 2 · Vocational · Electronics and Computer

Computer Programming

Implementing functions

about 3 minutes to read

Discussions
Topics in this sectionCreating PHP programs4 topics

A function is a reusable block of code that performs a specific task. Instead of writing the same code many times, you write it once inside a function and then call that function whenever you need it.

What is a Function?

A function is like a recipe: you define the steps once, and whenever you need to follow that recipe, you just refer to it by name. In PHP, functions help you organize your code, make it shorter, and avoid errors.

Defining a Function in PHP

To create a function, use the function keyword followed by a name, parentheses, and curly braces. The code you want to run goes inside the braces.

function greet() {
    echo "Hello, welcome to class!";
}

The function name should describe what it does. In PHP, function names are not case-sensitive, but it is good practice to use lowercase and underscores for readability.

Function Parameters

Parameters let you pass data into a function so it can work with different values. You list parameters inside the parentheses when defining the function.

function greetStudent($name) {
    echo "Hello, " . $name . "!";
}

When you call this function, you provide an actual value (an argument) that replaces the parameter:

greetStudent("Amina");  // Output: Hello, Amina!

You can have multiple parameters:

function addNumbers($num1, $num2) {
    $sum = $num1 + $num2;
    echo $sum;
}

Return Values

A function can send back a result using the return keyword. When return is executed, the function stops running and sends the value back to wherever the function was called.

function multiply($a, $b) {
    return $a * $b;
}

$result = multiply(5, 3);
echo $result;  // Output: 15

Calling a Function

After you define a function, you use it by writing its name with parentheses. If the function needs parameters, you put the values inside the parentheses.

// Define the function
function calculatePrice($price, $quantity) {
    return $price * $quantity;
}

// Call the function
$total = calculatePrice(1500, 4);
echo "Total: " . $total . " TSh";  // Output: Total: 6000 TSh

Worked Example

Consider a simple calculator that calculates the total cost of buying airtime. The function takes the price per unit and the number of units, then returns the total cost.

function calculateTotal($pricePerUnit, $units) {
    $total = $pricePerUnit * $units;
    return $total;
}

// Calculate cost for 5 units at 500 TSh each
$airtimeCost = calculateTotal(500, 5);
echo "You need to pay: " . $airtimeCost . " TSh";

Output:

You need to pay: 2500 TSh

This function can be reused any time you need to calculate a total — just call it with different values.

Real-life application

In Tanzania, small shop owners can use PHP functions to calculate profit from selling items. For example, a vendor at Mlimani City can write a function that takes the buying price and selling price of a bag of rice, then automatically calculates the profit for each sale, helping them track earnings quickly without doing the math manually every time.

How you'll be assessedProcess assessment · Outcome assessment · Knowledge assessment

Process assessment

  • Write PHP functions with inputs and outputs.
  • Use global and local variables appropriately.
  • Test function behavior.

Outcome assessment

Programs with reusable functions (e.g., calculating factorials, formatting strings, etc.).

Knowledge assessment

Detailed knowledge of:

Method used: The student should explain how to

  • define functions in PHP
  • Call functions in other parts of the PHP program

Principles: The student should explain the principles of:

  • procedural programming and modular design.

Theories: The student should explain:

  • The basic concepts of PHP functions and their definitions
  • Scope (global vs. local), recursion, and the role of functions in reducing code redundancy.

Circumstantial knowledge:

Detailed knowledge about:

  • Best practices for writing maintainable and reusable functions, such as meaningful naming and parameter validation.

Question

What is a function in PHP?

Sign in to submit your answer and have it count toward your mastery.

Sign in to practice

Tutor

Stuck? Ask me anything about this topic.

Sign in to ask the Sonza AI Tutor about this question.

Sign in to ask

Discussions

No questions yet

Sign in to ask
Loading discussions…