PHP Classes and Objects

PHP Classes and Objects

A class is a blueprint; an object is an instance created from it. Classes can have properties, methods, constants, and static members.

1 - Defining a Class

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

2 - Class Constants

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

3 - Static Members

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

Note: Use self:: to reference the current class in static context. Use static:: (late static binding) when you want the reference to resolve to the child class in inherited contexts.

-Tip-