×

php · level 3 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.