An object is one actual thing built from a class. The word instance means the same. You create it with new.
<?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();
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->namereads a property.$a->bark()calls a method.
Objects hold their own data
Changing one object does not affect another.
<?php
class Counter
{
public int $count = 0;
}
$one = new Counter();
$two = new Counter();
$one->count = 5;
echo $one->count . " and " . $two->count;
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.
<?php
class Box
{
public int $items = 1;
}
$a = new Box();
$b = $a; // same object
$b->items = 99;
echo $a->items;
99
To make a real copy, use clone.
<?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;
1 and 99
Compare objects
<?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
bool(true)
bool(false)
bool(true)
Check what an object is
<?php
class Cat {}
$cat = new Cat();
var_dump($cat instanceof Cat);
echo get_class($cat) . "\n";
echo $cat::class;
bool(true)
Cat
Cat
Objects in arrays
<?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";
}
Write: open
Test: done
Dynamic properties are deprecated
Creating a property that the class never declared still works, but PHP 8.2 deprecates it.
<?php
class Plain {}
$p = new Plain();
$p->surprise = "not declared";
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.
Each object is independent
Order object per order, one User per user.