Chapter 04 ยท OOP Foundations
Classes & Objects
This is the most important chapter in the whole course. Once you truly understand the difference between a class and an object, everything else in OOP becomes easy. Take it slowly and type every example.
The cookie cutter and the cookies
A class is a cookie cutter โ a template, a design, a plan. You cannot eat a cookie cutter! An object is a cookie made with that cutter โ a real thing you can actually use. One cutter can make endless cookies, and each cookie is separate: bite one and the others are untouched.
Other ways to picture it: a class is a house blueprint, objects are the actual houses built from it. A class is the admission form design, objects are the filled-in forms of real students.
Your first class
student.php<?php
class Student {
// Properties = the data each student will carry (variables that live inside the class)
public string $name = "";
public string $program = "";
// Method = a function that lives inside the class (a skill every student has)
public function introduce(): string {
return "Hi, I am $this->name and I study $this->program.";
}
}
Reading it piece by piece:
class Student { ... }โ "Here is the design for a thing called Student." Class names start with a Capital Letter by convention.- Properties (
$name,$program) โ variables that belong to the class. Every student made from this design will have its own copy of them. - Methods (
introduce()) โ functions that belong to the class. They describe what a student can do. publicโ means "anyone may access this". (Chapter 06 introduces the private option.)
Writing a class does not create any student. It's only the cutter, not a
cookie. To get a real object we must say the magic word: new.
Making objects with new
$s1 = new Student(); // cut the first cookie
$s2 = new Student(); // cut a second, completely separate cookie
$s1->name = "Chanda";
$s1->program = "BSc Computing";
$s2->name = "Mutinta";
$s2->program = "LLB";
echo $s1->introduce();
echo "<br>";
echo $s2->introduce();
Two new symbols to learn โ and they're the last new symbols for a while:
new Student()โ "build me a fresh object from the Student design."->โ the object operator, a little arrow. Read it as "'s" (apostrophe-s).$s1->nameis "s1's name".$s1->introduce()is "s1's introduce skill โ go!".
Notice that changing $s1's name did nothing to $s2. Each object has
its own copy of every property โ separate cookies.
The mysterious $this
Look inside introduce() again: it says $this->name. What is
$this?
$this simply means "me, myself". When you write a class you
are writing instructions for objects that don't exist yet โ so how can the code refer to "the
student's own name"? With $this. When $s1->introduce() runs,
$this means $s1. When $s2->introduce() runs,
$this means $s2. It's like the word "my" โ the same word, but it
points to whoever is speaking.
class Student {
public string $name = "";
public function shout(): string {
// "$this->name" = "MY OWN name, whoever I am"
return strtoupper($this->name) . " IS HERE!";
}
}
$a = new Student();
$a->name = "Bwalya";
echo $a->shout(); // $this was $a
$this
- Write
$this->name, not$this->$nameโ no second dollar sign after the arrow. $thisonly works inside a class. Using it in normal code outside a class is an error โ there is no "myself" out there.
Methods can use other methods
Objects can call their own skills using $this too. Watch a slightly bigger,
realistic example:
class BankAccount {
public string $owner = "";
public float $balance = 0;
public function deposit(float $amount): void {
$this->balance += $amount;
}
public function withdraw(float $amount): string {
if ($amount > $this->balance) {
return "Sorry $this->owner, insufficient funds.";
}
$this->balance -= $amount;
return "Done. " . $this->statement(); // calling my own other method!
}
public function statement(): string {
return "$this->owner's balance is K" . number_format($this->balance, 2);
}
}
$acc = new BankAccount();
$acc->owner = "Thandiwe";
$acc->deposit(1000);
echo $acc->withdraw(250);
echo "<br>";
echo $acc->withdraw(5000);
See how natural it reads? The account protects itself โ the withdraw method refuses to go below zero. Data and rules travelling together: that's OOP working for you already.
Objects in arrays โ a class register
Objects are values like any other, so you can put them in arrays and loop over them:
$class = [];
$s = new Student(); $s->name = "Chanda"; $class[] = $s;
$s = new Student(); $s->name = "Mutinta"; $class[] = $s;
$s = new Student(); $s->name = "Bwalya"; $class[] = $s;
foreach ($class as $student) {
echo $student->name . "<br>";
}
This exact pattern โ "a list of objects, looped over to build HTML" โ is how every real application displays a table of students, products or messages. Remember it.
Create a class Phone with properties $brand and
$batteryLevel (start it at 100). Give it a method use30Minutes() that
reduces the battery by 10, and a method status() that returns
"Samsung battery: 80%" style text. Create one phone, use it twice, and print the status.
Show solution
<?php
class Phone {
public string $brand = "";
public int $batteryLevel = 100;
public function use30Minutes(): void {
$this->batteryLevel -= 10;
}
public function status(): string {
return "$this->brand battery: $this->batteryLevel%";
}
}
$p = new Phone();
$p->brand = "Samsung";
$p->use30Minutes();
$p->use30Minutes();
echo $p->status();
Which keyword actually creates an object from a class?
Inside a method, what does $this mean?
If you change $s1->name, what happens to $s2->name?
- Class = cookie cutter (the design). Object = cookie (the real thing).
new ClassName()creates an object; each object has its own copies of the properties.- Properties = variables inside a class. Methods = functions inside a class.
- The arrow
->reads as "'s":$s1->nameis "s1's name". $thismeans "me, myself" โ the object whose method is running.- Objects can live in arrays;
foreachover object lists is the pattern behind every data table on the web.