php · level 3 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Some things belong to the class, not to any one object.
A is a fixed value that lives on the class, like const BOILING = 100;. Read it with the class name and ::, as in Temperature::BOILING. Inside the class, self:: means this class.
A method belongs to the class too, so you call it without building an object first: Temperature::fromFahrenheit(212). This one is a . It converts the units, builds a proper object with new self(...) and returns it, and its name says exactly what it expects.
A static property is one box shared by every object of the class.
<?php
class Temperature {
const BOILING = 100;
public function __construct(public float $celsius) {}
public static function fromFahrenheit(float $f): self {
return new self(($f - 32) * 5 / 9);
}
public function isBoiling(): bool { return $this->celsius >= self::BOILING; }
}
$kettle = Temperature::fromFahrenheit(212);
echo "$kettle->celsius degrees\n";
if ($kettle->isBoiling()) {
echo "Time for tea!\n";
} Use -> for things on an object and :: for things on the class.
guess first
Three visitors walk in. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Visitor {
public static int $count = 0;
public function __construct(public string $name) {
self::$count++;
}
}
new Visitor("Mia");
new Visitor("Leo");
$sam = new Visitor("Sam");
echo Visitor::$count . "\n";
your turn
Your turn. Measure a walk in miles.
In the first blank, type the name of the constant that holds kilometres per mile. In the second, type how many miles your walk is.
fix it
The lift cannot find its own limit. Fix it.
- The error is
Undefined constant "MAX_PEOPLE"on line 6. It is defined on line 3, so where is PHP looking? - A class constant lives on the class. On its own, the name makes PHP search outside every class.
- Change
MAX_PEOPLEon line 6 toself::MAX_PEOPLE, then run it.
nailed it
you gave your classes their own tools. :D
conststores a fixed value on the class itself.- Reach class members with
::, and useself::inside the class. - A named constructor is a static method that builds an object.
new words in your collection
- static
- class constant
- named constructor
This lesson isn’t saved. A free account remembers every lesson you finish.