Classes & Objects
class User {
// Properties with types
public string \$name;
private int \$age;
protected string \$email;
// Constructor (PHP 8+ promoted properties)
public function __construct(
public string \$username,
private string \$password,
) { }
// Methods
public function getName(): string {
return \$this->name;
}
// Static methods
public static function createGuest(): self {
return new self("guest", "");
}
}
// Instantiation
\$user = new User("alice", "secret");
echo \$user->username;
Visibility
- public — accessible everywhere
- protected — accessible in class and subclasses
- private — accessible only in defining class