PHP Classes/Objects

JA JASWANT Updated 19 Oct 2026
7 min read ·Lesson 123 of 143
In this post

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

PartMeaning
class ProductDeclares 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->priceInside 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

  1. new Product() creates a new object with the default property values.
  2. -> accesses properties ($pen->name) and calls methods ($pen->priceWithTax()).
  3. $pen and $lamp are independent objects: each has its own name and price.
  4. The method uses $this->price, so the same code calculates the correct price for whichever object it is called on.
  5. Assigning 20 (an integer) to a float property converts it to 20.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
ToolReturns
var_dump($obj)Class name, object ID (#1), and all properties with types
get_class($obj)The class name of an object
$obj instanceof ClassNameWhether the object is an instance of a class (or its subclasses/interfaces)
ClassName::classThe 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).
  • clone creates 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

  1. Each database-like row is turned into a Product object.
  2. The objects carry both data and behavior: isInStock() and label() are available on every product.
  3. A method can call another method of the same object ($this->isInStock() inside label()).
  4. 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 clone for copies.
  • Use instanceof and ::class instead of comparing class names as strings.

Official reference: https://www.php.net/manual/en/language.oop5.basic.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning
Ask about this post
AI Ask about this post

Ask questions about PHP Classes/Objects and get answers drawn from it.

Signed-in readers only.