Classes
Define a class
Properties and methods live on the class. Construct with new.
<?php
class User {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function label(): string {
return "User: {$this->name}";
}
}
$u = new User("Ada");
echo $u->label(), "\n";
Visibility
Use public, private, and protected to control access.
class Counter {
private int $n = 0;
public function inc(): void { $this->n++; }
public function value(): int { return $this->n; }
}
Inheritance briefly
A class can extend another with extends.
OOP tips
- One class per file is a common PSR style
- Name classes in StudlyCase
- Keep constructors light
- Learn interfaces and namespaces as projects grow
Comments
One comment per signed-in account. Comments are saved with this page’s URL.