A class is a blueprint; an object is an instance created from it.
class Product
{
public string $name;
public float $price;
private int $stock = 0;
public function __construct(string $name, float $price)
{
$this->name = $name;
$this->price = $price;
}
public function restock(int $quantity): void
{
$this->stock += $quantity;
}
public function getStock(): int
{
return $this->stock;
}
}
$laptop = new Product('Laptop', 999.99);
$laptop->restock(10);
echo $laptop->name; // 'Laptop'
echo $laptop->getStock(); // 10
Visibility modifiers control access: public (accessible from anywhere), protected (accessible from the class and its subclasses), private (accessible only from within the same class).
Constructor property promotion (PHP 8.0+) removes the boilerplate of declaring properties separately:
class Product
{
public function __construct(
public string $name,
public float $price,
private int $stock = 0,
) {}
}
Static properties and methods belong to the class itself, not any instance: ClassName::$staticProp and ClassName::staticMethod(), useful for counters, factories, or utility methods that don't need object state.