A class is a blueprint; an object is an instance created from it. Classes can have properties, methods, constants, and static members.
class User {
// Property with default
public bool $isActive = true;
// Constructor with promotion
public function __construct(
private int $id,
private string $name,
private string $email
) {}
public function getId(): int { return $this->id; }
public function getName(): string { return $this->name; }
public function getEmail(): string { return $this->email; }
}
$user = new User(1, "Alice", "[email protected]");
echo $user->getName(); // Alice
class Circle {
const PI = M_PI;
public function __construct(private float $radius) {}
public function area(): float {
return self::PI * $this->radius ** 2;
}
}
echo Circle::PI; // 3.1415926535898
class IdGenerator {
private static int $next = 1;
public static function generate(): int {
return self::$next++;
}
}
echo IdGenerator::generate(); // 1
echo IdGenerator::generate(); // 2
echo IdGenerator::generate(); // 3