Skip to content

PHP Tutorial Object-Oriented PHP

Objects

Lesson 199 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

An object is one actual thing built from a class. The word instance means the same. You create it with new.

index.php
PHP
<?php
class Dog
{
    public string $name = "";

    public function bark(): string
    {
        return $this->name . " says woof!";
    }
}

$a = new Dog();
$a->name = "Bruno";

$b = new Dog();
$b->name = "Luna";

echo $a->bark() . "\n";
echo $b->bark();
Output
OUTPUT
Bruno says woof!
Luna says woof!

$a and $b are two separate objects from the same class. Each has its own name.

The arrow ->

Use -> to reach inside an object:

  • $a->name reads a property.
  • $a->bark() calls a method.

Objects hold their own data

Changing one object does not affect another.

index.php
PHP
<?php
class Counter
{
    public int $count = 0;
}

$one = new Counter();
$two = new Counter();

$one->count = 5;

echo $one->count . " and " . $two->count;
Output
OUTPUT
5 and 0

Objects are handled by handle (reference)

When you assign an object to another variable, you copy the handle, not the object. Both variables point to the same object.

index.php
PHP
<?php
class Box
{
    public int $items = 1;
}

$a = new Box();
$b = $a;          // same object

$b->items = 99;

echo $a->items;
Output
OUTPUT
99

To make a real copy, use clone.

index.php
PHP
<?php
class Box
{
    public int $items = 1;
}

$a = new Box();
$b = clone $a;    // a separate copy

$b->items = 99;

echo $a->items . " and " . $b->items;
Output
OUTPUT
1 and 99

Compare objects

index.php
PHP
<?php
class Point
{
    public function __construct(public int $x = 0, public int $y = 0) {}
}

$a = new Point(1, 2);
$b = new Point(1, 2);
$c = $a;

var_dump($a == $b);    // same class, same values
var_dump($a === $b);   // different objects
var_dump($a === $c);   // the same object
Output
OUTPUT
bool(true)
bool(false)
bool(true)

Check what an object is

index.php
PHP
<?php
class Cat {}
$cat = new Cat();

var_dump($cat instanceof Cat);
echo get_class($cat) . "\n";
echo $cat::class;
Output
OUTPUT
bool(true)
Cat
Cat

Objects in arrays

index.php
PHP
<?php
class Task
{
    public function __construct(public string $title, public bool $done = false) {}
}

$tasks = [new Task("Write"), new Task("Test", true)];

foreach ($tasks as $task) {
    echo $task->title . ": " . ($task->done ? "done" : "open") . "\n";
}
Output
OUTPUT
Write: open
Test: done

Dynamic properties are deprecated

Creating a property that the class never declared still works, but PHP 8.2 deprecates it.

index.php
PHP
<?php
class Plain {}

$p = new Plain();
$p->surprise = "not declared";
Output
OUTPUT
Deprecated: Creation of dynamic property Plain::$surprise is deprecated in /path/to/index.php on line 5

Declare every property in the class. That also protects you from typos.

lightbulb
Each object is independent
Use a new object for each thing you model. One Order object per order, one User per user.