php · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a blueprint. An object is one thing built from it.
You have used objects such as a PDO database link and called their methods with ->. Now you design your own. A class describes a kind of thing, like a pet: the data each one holds and what it can do. Writing new Pet() builds an object from that blueprint.
Each piece of data is a , a variable living inside the object. Each action is a method, written inside the class like a function. You reach both with ->, so $rex->name is Rex's name and $rex->speak() runs his method.
Inside a method, means the object the method was called on. Two pets share one blueprint, but never their data.
<?php
class Pet {
public string $name = "";
public string $sound = "";
public function speak(): string {
return "$this->name says $this->sound!";
}
}
$rex = new Pet();
$rex->name = "Rex";
$rex->sound = "woof";
echo $rex->speak() . "\n"; Write public before each property and method for now, and you will meet its opposite in two lessons' time.
guess first
Two counters from one class. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Counter {
public int $count = 0;
public function add(): void {
$this->count++;
}
}
$a = new Counter();
$b = new Counter();
$a->add();
$a->add();
$b->add();
echo "$a->count and $b->count\n";
your turn
Your turn. Stock the tuck shop.
Type the name of a snack in the quotes and its price in pence in the second blank, then run it to see your object label itself.
fix it
The robot forgot its own name. Fix it.
- Read the error:
Undefined variable $nameon line 6. The property is right there on line 3, so why can the method not see it? - Inside a method, a bare
$nameis an ordinary local variable. Properties live on the object. - Change
$nameon line 6 to$this->name, then run it.
nailed it
you built your first objects. :D
- A class is a blueprint, and
newbuilds an object from it. - Properties hold data and methods act, both reached with
->. $thismeans the object a method was called on.
new words in your collection
- class
- property
- $this
This lesson isn’t saved. A free account remembers every lesson you finish.