PHP Classes/Objects

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 149 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.