A PHP class is a blueprint defining properties (data) and methods (functions), while an object is a concrete instance created from that class using the new keyword. Inside a class method, the $this pseudo-variable refers to the current object instance.
Modern PHP supports typed properties, strict method signatures, and readonly properties (PHP 8.1+) that cannot be overwritten after initialization.
<?php
declare(strict_types=1);
class Product
{
public string $name;
public float $price;
private int $stock = 0;
public function setStock(int $quantity): void
{
if ($quantity < 0) {
throw new InvalidArgumentException('Stock cannot be negative.');
}
$this->stock = $quantity;
}
public function isAvailable(): bool
{
return $this->stock > 0;
}
}
$keyboard = new Product();
$keyboard->name = 'Compact Mechanical Keyboard';
$keyboard->price = 79.00;
$keyboard->setStock(12);
echo "{$keyboard->name} available: " . ($keyboard->isAvailable() ? 'Yes' : 'No') . PHP_EOL;
var_dump($keyboard instanceof Product);
instanceofUnlike PHP arrays and scalars—which copy on assignment—PHP variables hold object handles pointing to the same instance in memory. If you write $b = $a; and change $b->name, $a->name reflects that change too; use clone $a when you truly need an independent copy.
Use $item instanceof Product to verify an object belongs to a specific class or implements an interface before calling its methods.
public string $name; before assigning a value throws an Error: Typed property must not be accessed before initialization. Initialize properties inline or in __construct().$this inside static methods: Static methods belong to the class, not an instance, so $this does not exist inside them.clone creates a shallow copy; implement __clone() if nested child objects also need duplicating.-> mean in PHP?The object operator -> accesses a property or calls a method on an object instance, such as $user->getName().
Yes. Every new Product() call allocates a separate object instance with its own property values in memory.
readonly class do in PHP 8.2+?Marking a class readonly automatically makes all its declared properties immutable once initialized in the constructor—great for value objects and DTOs.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.