Panafrikan PHP

An educational initiative by EColSi

Discover EColSi
Choose your language
Explore the course

B06 | Create reusable PHP functions

Basic level · Lesson B06

B06 | Create reusable PHP functions

B06 | Create reusable PHP functions

Result: small library to measure progress.
Core concept: A function names a responsibility and returns a result.
Guideline time: 75–100 minutes.

What do you do when a stone appears three times?

You turn it into a function. This way you correct the rule in one place, you can test it and you better express the intention of the program.

Previous connection

In B05 we repeat a presentation. Now we will avoid repeating logic.

Concepts

A function can receive parameters, validate assumptions and return a value. Local scope prevents a function from accidentally depending on external variables.

Guided laboratory

<?php
function progressPercentage(float $completed, float $goal): float
{
    if ($goal <= 0) {
        return 0;
    }

    return min(100, ($completed / $goal) * 100);
}

echo round(progressPercentage(6, 10), 1) . "%";

The function does not print: it calculates and returns. The presentation decides how to show.

Medium Mission

Create three functions: percentage, sessions required, and progress message. Use clear names and test each one with two values.

University Extension

Define contracts using types, decide how to handle invalid input, and compare returning a neutral value to throwing an exception. At this level you implement a policy and document your limit.

Tests

Normal goal, zero goal, progress greater than goal and decimals.

Delivery

Send functions, test table and sole responsibility explanation. SEND TO TUTOR.

Next: B07 — Catalog with arrangements.

Comments

Popular posts from this blog

Bem-vindo ao Panafrikan PHP: aprenda, construa e compartilhe

Bienvenue sur Panafrikan PHP : apprenez, créez et partagez