<?php OOP: Zero to Hero Chapter 02 of 20

Chapter 02 ยท Getting Started

PHP Refresher: The Basics

Before we build with objects, we need solid bricks. This chapter is a fast, friendly tour of plain PHP: variables, data types, arrays, conditions, loops and functions. If you already know these, skim it โ€” but don't skip the functions section, because OOP is built on top of it.

Variables โ€” labelled boxes

๐Ÿ“ฆ
Real-world analogy

A variable is a labelled box. You write a name on the label, put something inside, and later you can open the box by calling its name. In PHP every label starts with a dollar sign $.

<?php
$name = "Chanda";        // a box called $name holding text
$age  = 21;              // a box holding a whole number
$fee  = 4500.50;         // a box holding a decimal number
$isRegistered = true;    // a box holding yes/no (true/false)

echo "Student: " . $name . ", Age: " . $age;
Student: Chanda, Age: 21

The dot . glues pieces of text together โ€” it's called concatenation. There's also a shortcut: if you use double quotes, PHP looks inside the text and swaps variables for their values automatically:

echo "Student: $name, Age: $age";   // same result, less typing
Note

Double quotes " " read variables inside them. Single quotes ' ' do not โ€” they print everything literally. Both are useful; just know the difference.

Data types you'll meet daily

TypeExampleEveryday meaning
string"Lusaka"Text โ€” anything in quotes
int42Whole numbers
float3.75Decimal numbers
booltrue / falseA light switch: on or off
array["a", "b"]A list of boxes in one big box
nullnullAn empty box โ€” nothing inside yet
objectcoming in Chapter 04!The star of this course

Arrays โ€” a box with compartments

๐Ÿฅš
Real-world analogy

An array is like an egg tray: one container, many compartments, each with a position number (starting from 0, because programmers count from zero!).

$courses = ["Maths", "Physics", "Programming"];

echo $courses[0];   // Maths   (first compartment)
echo $courses[2];   // Programming

Even more useful is the associative array, where each compartment has a name instead of a number โ€” like an envelope with labelled pockets:

$student = [
    "name"    => "Mutinta",
    "age"     => 19,
    "program" => "BSc Computing"
];

echo $student["name"];      // Mutinta
echo $student["program"];   // BSc Computing

Keep this picture in mind โ€” an associative array looks suspiciously like a "thing with properties"... which is exactly what an object is. We're laying the groundwork already!

Making decisions โ€” if / else

$marks = 72;

if ($marks >= 75) {
    echo "Distinction!";
} elseif ($marks >= 50) {
    echo "Pass. Well done.";
} else {
    echo "Fail. Let's revise and try again.";
}
Pass. Well done.

Common comparison signs: == equal, != not equal, > greater, < less, >=, <=. Use && for "and", || for "or".

Classic beginner trap

One equals sign = means "put this into the box" (assignment). Two equals signs == means "are these the same?" (comparison). Writing if ($age = 18) by mistake assigns 18 instead of checking it! There is also ===, which checks value and type โ€” the safest choice.

Loops โ€” doing things many times

// Print 1 to 5
for ($i = 1; $i <= 5; $i++) {
    echo "Number $i <br>";
}

// Walk through every item in an array โ€” you will use this CONSTANTLY
$courses = ["Maths", "Physics", "Programming"];
foreach ($courses as $course) {
    echo "I am studying $course <br>";
}
Number 1 Number 2 Number 3 Number 4 Number 5 I am studying Maths I am studying Physics I am studying Programming

With associative arrays, foreach can give you both the label and the value:

$student = ["name" => "Mutinta", "age" => 19];

foreach ($student as $key => $value) {
    echo "$key: $value <br>";
}
name: Mutinta age: 19

Functions โ€” recipes you write once

๐Ÿซ–
Real-world analogy

A function is a recipe. You write "How to Make Tea" once. From then on, whenever anyone says "make tea", the same steps run. Recipes can accept ingredients (parameters) and hand back a finished product (a return value).

function makeGreeting($name) {
    return "Good morning, $name! Welcome to class.";
}

echo makeGreeting("Bwalya");
echo makeGreeting("Thandiwe");
Good morning, Bwalya! Welcome to class. Good morning, Thandiwe! Welcome to class.

Two important words:

Parameters can have default values, and you can (and should) declare types:

function calculateFee(float $tuition, float $discount = 0): float {
    return $tuition - $discount;
}

echo calculateFee(5000);        // 5000 (no discount given)
echo calculateFee(5000, 750);   // 4250

The float before each parameter and after the ): tells PHP: "these must be numbers, and the answer will be a number." Typed code catches mistakes early โ€” we will use types throughout this course.

โœ๏ธ Try it yourself

Write a function gradeOf($marks) that returns "A" for 75 and above, "B" for 65โ€“74, "C" for 50โ€“64 and "F" below 50. Then loop through the array [82, 67, 45, 91] and print each mark with its grade.

Show solution
<?php
function gradeOf(int $marks): string {
    if ($marks >= 75) return "A";
    if ($marks >= 65) return "B";
    if ($marks >= 50) return "C";
    return "F";
}

$results = [82, 67, 45, 91];
foreach ($results as $marks) {
    echo "$marks => " . gradeOf($marks) . "<br>";
}
82 => A 67 => B 45 => F 91 => A
Quick quiz

Which loop is designed specifically for walking through arrays?

Quick quiz

What does return do inside a function?

๐Ÿ”‘ Key points
  • Variables are labelled boxes: $name = "Chanda";
  • Arrays hold many values; associative arrays use named keys โ€” a preview of objects.
  • if / elseif / else makes decisions; use === for safe comparison.
  • foreach is your everyday loop for arrays.
  • Functions are reusable recipes: parameters go in, a return value comes out.
  • Declare types (int, string, float) to catch bugs early.