Skip to content

3. Classes and objects

A task has more than a title. This step makes each task an object of the class Task:

<?nvs
// This program makes each task an object with a title and a done flag.
class Task
{
public string $title;
public bool $done = false;
// `constructor` runs when you write `new Task(...)`.
public function constructor(string $title)
{
$this->title = $title;
}
public function line(): string
{
return ($this->done ? '[x] ' : '[ ] ') . $this->title;
}
}
array<Task> $tasks = [new Task('Buy milk'), new Task('Call Ada')];
// `->` reads or changes a property of an object.
$tasks[0]->done = true;
foreach ($tasks as Task $task) {
echo $task->line(), "\n";
}
Output
[x] Buy milk
[ ] Call Ada

Each property has a type. $done has the default value false, so a new task is not done.

The method named constructor runs when you write new Task("Buy milk"). Inside a method, $this is the object the method was called on.

array<Task> is an array of Task objects. $tasks[0]->done = true changes the first task, and the loop prints both.

Read more in Syntax: declaring a class and Syntax: properties.

Next: step 4, values that may be missing.