An object is a value that bundles data (called properties) and actions (called methods) in one package. You create objects from a blueprint called a class.
Think of a class as a cookie cutter and objects as the cookies.
<?php
class Car
{
public string $brand = "Tata";
public function honk(): string
{
return "Beep!";
}
}
$car = new Car();
echo $car->brand . "\n";
echo $car->honk();
Tata
Beep!
class Cardefines the blueprint.new Car()creates one object.->reaches inside the object to read a property or call a method.
Checking an object
<?php
class Car {}
$car = new Car();
var_dump($car instanceof Car);
echo get_debug_type($car);
bool(true)
Car
The built-in stdClass
PHP has an empty class called stdClass for quick, plain objects. You will often meet it when decoding JSON.
<?php
$point = new stdClass();
$point->x = 10;
$point->y = 20;
echo $point->x + $point->y;
30
Objects are handled by reference
Assigning an object to another variable does not copy it. Both variables point to the same object.
<?php
$a = new stdClass();
$a->name = "first";
$b = $a;
$b->name = "changed";
echo $a->name;
changed