PHP Classes / Objects
A class declares a new type — its properties and methods. new ClassName(...) creates an instance.
Basic class
PHP
class Person {
public string $name;
public int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function greet(): string {
return "Hi, I am {$this->name}";
}
}
$p = new Person('Ada', 36);
echo $p->greet();
Constructor property promotion (8.0+)
Shrink boilerplate — declare and assign at the same time:
PHP
class Person {
public function __construct(
public string $name,
public int $age,
) {}
public function greet(): string {
return "Hi, I am {$this->name}";
}
}
Readonly properties (8.1+)
PHP
class Money {
public function __construct(
public readonly int $cents,
public readonly string $currency = 'USD',
) {}
}
$m = new Money(1000);
// $m->cents = 2000; // Error — cannot modify readonly
Methods
PHP
class Counter {
private int $count = 0;
public function bump(): self {
$this->count++;
return $this; // for fluent chaining
}
public function value(): int {
return $this->count;
}
}
echo (new Counter())->bump()->bump()->bump()->value(); // 3
Tip: Reach for property promotion + typed properties by default. The old "declare property then assign in constructor" dance is now noise.
Example
Example
<?php
class Person {
public function __construct(
public string $name,
public int $age,
) {}
public function greet(): string {
return "Hi, I am {$this->name}";
}
}
$p = new Person('Ada', 36);
echo $p->greet();
Try it Yourself »
Exercise
Declare a class.
Person {}
Five letters.
Discussion
Loading…