Classes and Objects
class Dog { ... } defines a class; new Dog("Rex") creates an instance of it. __construct() is PHP's constructor — a method with that exact reserved name, called automatically when new runs. Inside any method, $this refers to the current instance, and -> (never a dot) is how you reach a property or call a method on an object: $this->name, $d->bark().
<?php
class Dog {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function bark() {
return "$this->name says Woof!";
}
}
$d = new Dog("Rex");
echo $d->bark(), "\n";
echo $d->name, "\n";
Rex says Woof! Rex
new Dog("Rex") called __construct("Rex"), which stored "Rex" on $this->name. Notice "$this->name says Woof!" interpolated $this->name directly inside a double-quoted string, with no extra braces needed for this simple property-access case — the same interpolation rule from the strings lesson, extended to object properties. Next: visibility and encapsulation — public, private, protected, and why most real PHP classes expose getters instead of raw public properties.
Practice exercise
Write a Car class with a public $brand property, a constructor that sets it, and a drive() method returning "$brand is driving." — then echo (new Car("Toyota"))->drive().