PHP Classes/Objects
PHP Classes and Objects: Defining Blueprints and Instances
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.
Defining a Class and Creating Objects
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);
Reference Semantics and instanceof
Unlike 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.
Common Mistakes to Avoid
- Reading an uninitialized typed property: Accessing
public string $name;before assigning a value throws anError: Typed property must not be accessed before initialization. Initialize properties inline or in__construct(). - Using
$thisinside static methods: Static methods belong to the class, not an instance, so$thisdoes not exist inside them. - Cloning objects containing nested objects blindly:
clonecreates a shallow copy; implement__clone()if nested child objects also need duplicating.
Frequently Asked Questions
What does -> mean in PHP?
The object operator -> accesses a property or calls a method on an object instance, such as $user->getName().
Can I create multiple independent objects from one class?
Yes. Every new Product() call allocates a separate object instance with its own property values in memory.
What does 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.