PHP Classes/Objects
Classes and Objects In simple terms: A class is a blueprint — like the design of a product in a catalog. An object is an actual thing built from that blueprint — like a specific product in your wareho
Classes and Objects
In simple terms: A class is a blueprint — like the design of a product in a catalog. An object is an actual thing built from that blueprint — like a specific product in your warehouse. One Product class can be used to create thousands of product objects, each with its own name and price.
Technically: A class declares properties (variables that hold an object's data) and methods (functions that define its behavior). The new operator creates an object — an instance of the class — with its own copy of the properties. Methods are called on objects with the object operator ->.
Class Product (blueprint) Objects (instances)
┌─────────────────────────┐ ┌──────────────────────┐
│ properties: name, price │ new → │ name: "Gel Pen" │
│ methods: priceWithTax() │ │ price: 20 │
└─────────────────────────┘ └──────────────────────┘
┌──────────────────────┐
new → │ name: "Desk Lamp" │
│ price: 1299 │
└──────────────────────┘
Defining a Class
Syntax
class ClassName
{
// properties
// methods
}
Example
<?php
class Product
{
public string $name = '';
public float $price = 0.0;
public function priceWithTax(float $taxPercent = 18): float
{
return round($this->price * (1 + $taxPercent / 100), 2);
}
}
Parts of the Class
| Part | Meaning |
|---|---|
class Product | Declares a class named Product |
public string $name = ''; | A property with visibility public, type string, and default value '' |
public function priceWithTax(...) | A method — a function that belongs to the class |
$this->price | Inside a method, $this refers to the object the method was called on (see The $this Keyword) |
Naming Conventions
- Class names use PascalCase:
Product,ShoppingCart,InvoiceGenerator. - Each class is usually stored in its own file named after the class (
Product.php), which enables autoloading (see Autoloading Classes). - Names should be nouns describing what the object is.
Creating Objects With new
<?php
class Product
{
public string $name = '';
public float $price = 0.0;
public function priceWithTax(float $taxPercent = 18): float
{
return round($this->price * (1 + $taxPercent / 100), 2);
}
}
$pen = new Product();
$pen->name = 'Gel Pen';
$pen->price = 20;
$lamp = new Product();
$lamp->name = 'Desk Lamp';
$lamp->price = 1299;
echo "{$pen->name}: ₹{$pen->priceWithTax()}\n";
echo "{$lamp->name}: ₹{$lamp->priceWithTax()}\n";
Output
Gel Pen: ₹23.6
Desk Lamp: ₹1532.82
How It Works
new Product()creates a new object with the default property values.->accesses properties ($pen->name) and calls methods ($pen->priceWithTax()).$penand$lampare independent objects: each has its ownnameandprice.- The method uses
$this->price, so the same code calculates the correct price for whichever object it is called on. - Assigning
20(an integer) to afloatproperty converts it to20.0.
Setting properties one by one after new is shown here for clarity. In real code, objects are usually given their data through a constructor, so they are never in an incomplete state (see PHP Constructor).
Inspecting Objects
<?php
class Product
{
public string $name = '';
public float $price = 0.0;
}
$pen = new Product();
$pen->name = 'Pen';
$pen->price = 20;
var_dump($pen);
echo get_class($pen) . "\n";
var_dump($pen instanceof Product);
echo Product::class . "\n";
Output
object(Product)#1 (2) {
["name"]=>
string(3) "Pen"
["price"]=>
float(20)
}
Product
bool(true)
Product
| Tool | Returns |
|---|---|
var_dump($obj) | Class name, object ID (#1), and all properties with types |
get_class($obj) | The class name of an object |
$obj instanceof ClassName | Whether the object is an instance of a class (or its subclasses/interfaces) |
ClassName::class | The fully qualified class name as a string, resolved at compile time |
The #1 is an internal object identifier, unique among the objects alive at that moment.
Objects Are Handled by Reference-Like Handles
Arrays are copied when assigned to another variable. Objects behave differently: a variable holds a handle (an identifier) to the object, and assigning it copies only the handle. Both variables then refer to the same object.
<?php
class Product
{
public string $name = '';
}
$a = new Product();
$a->name = 'Pen';
$b = $a; // same object
$b->name = 'Notebook';
echo $a->name . "\n";
$c = clone $a; // a separate copy
$c->name = 'Lamp';
echo $a->name . "\n";
echo $c->name . "\n";
Output
Notebook
Notebook
Lamp
Why This Matters
- Changing an object through one variable is visible through all variables that refer to it — including inside functions it was passed to (see Function Arguments).
clonecreates a new object with copies of the properties. Cloning has subtleties with nested objects, covered in Object Cloning.
Creating an Object and Using It Immediately
<?php
class Greeting
{
public function text(string $name): string
{
return "Hello, $name!";
}
}
echo (new Greeting())->text('Asha') . "\n"; // all PHP versions
echo new Greeting()->text('Bala') . "\n"; // PHP 8.4+
Output
Hello, Asha!
Hello, Bala!
Since PHP 8.4, the parentheses around new Greeting() are no longer required when calling a method directly on the new object.
stdClass and Converting Arrays
stdClass is PHP's generic empty class. It appears when decoding JSON without true, or when casting an array to an object:
<?php
$point = (object) ['x' => 3, 'y' => 4];
echo get_class($point) . "\n";
echo $point->x + $point->y . "\n";
$data = (array) $point;
echo $data['y'] . "\n";
Output
stdClass
7
4
stdClass objects accept any property, but they offer no types, no validation, and no methods. For data with meaning in your application, define a real class.
Practical Example: A Small Product Catalog
<?php
class Product
{
public string $sku = '';
public string $name = '';
public float $price = 0.0;
public int $stock = 0;
public function isInStock(): bool
{
return $this->stock > 0;
}
public function label(): string
{
$availability = $this->isInStock() ? "{$this->stock} in stock" : 'out of stock';
return sprintf('%s (%s) — ₹%s, %s', $this->name, $this->sku, number_format($this->price, 2), $availability);
}
}
$rows = [
['sku' => 'PEN-01', 'name' => 'Gel Pen', 'price' => 20, 'stock' => 120],
['sku' => 'LAMP-01', 'name' => 'Desk Lamp', 'price' => 1299, 'stock' => 0],
];
$catalog = [];
foreach ($rows as $row) {
$product = new Product();
$product->sku = $row['sku'];
$product->name = $row['name'];
$product->price = $row['price'];
$product->stock = $row['stock'];
$catalog[] = $product;
}
foreach ($catalog as $product) {
echo $product->label() . "\n";
}
$available = array_filter($catalog, fn(Product $p): bool => $p->isInStock());
echo count($available) . " product(s) available\n";
Output
Gel Pen (PEN-01) — ₹20.00, 120 in stock
Desk Lamp (LAMP-01) — ₹1,299.00, out of stock
1 product(s) available
Step-by-Step Explanation
- Each database-like row is turned into a
Productobject. - The objects carry both data and behavior:
isInStock()andlabel()are available on every product. - A method can call another method of the same object (
$this->isInStock()insidelabel()). - Objects work with array functions:
array_filter()with a typed callback selects available products.
Compared with plain arrays, the logic for "is this product available?" and "how is a product displayed?" now lives in one place — the class — instead of being repeated wherever products are used.
Common Mistakes
Forgetting new
$product = Product(); // Error: Call to undefined function Product()
Fix: $product = new Product();.
Using . Instead of ->
Effect: $product.name is a concatenation attempt, not property access.
Fix: Use $product->name.
Writing $ Before the Property Name
Effect: $product->$name uses the value of the variable $name as the property name (dynamic access).
Fix: $product->name.
Expecting Assignment to Copy an Object
Effect: Changes through one variable unexpectedly appear in the other.
Fix: Use clone when an independent copy is needed.
Using Arrays or stdClass for Important Data
Effect: No validation, no autocompletion, and logic scattered across the code.
Fix: Define classes for the concepts of your application.
Best Practices
- Name classes with PascalCase nouns and store each class in its own file.
- Declare property types and keep related behavior in methods of the same class.
- Initialize objects completely, preferably through constructors.
- Remember that objects are passed by handle; use
clonefor copies. - Use
instanceofand::classinstead of comparing class names as strings.
Official reference: https://www.php.net/manual/en/language.oop5.basic.php