TExcelTAD
Home › PHP › PHP Classes & Objects

PHP Classes & Objects

A class defines what an object knows (its properties) and what it can do (its methods). You create objects from a class with the new keyword. Each object gets its own copy of the properties, so changing one object does not affect another.

Defining a class

A class name is usually written in PascalCase. Inside the braces you declare properties and methods:

php · try it yourself
<?php
class Lamp {
    public string $color = 'white';
    public bool $on = false;

    public function toggle(): void {
        $this->on = !$this->on;
    }

    public function describe(): string {
        $state = $this->on ? 'on' : 'off';
        return "A {$this->color} lamp that is {$state}";
    }
}

$desk = new Lamp();
$desk->color = 'green';
$desk->toggle();

$floor = new Lamp();

echo $desk->describe() . "\n";
echo $floor->describe() . "\n";
A green lamp that is on
A white lamp that is off

Notice:

  • public string $color = 'white'; declares a typed property with a default value.
  • Inside a method, $this refers to the object the method was called on.
  • Properties are accessed without a $ after the arrow: $this->color, not $this->$color.

Typed properties

Since PHP 7.4 properties can carry a type. PHP then refuses values of the wrong type (in strict mode) or converts compatible scalars. A typed property without a default is uninitialized until you assign it, and reading it throws an Error:

php · try it yourself
<?php
declare(strict_types=1);

class Book {
    public string $title;
    public int $pages = 0;
}

$b = new Book();
try {
    echo $b->title;
} catch (Error $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

$b->title = 'PHP Basics';
try {
    $b->pages = 'many';
} catch (TypeError $e) {
    echo "TypeError: " . $e->getMessage() . "\n";
}

echo "{$b->title} has {$b->pages} pages\n";
Error: Typed property Book::$title must not be accessed before initialization
TypeError: Cannot assign string to property Book::$pages of type int
PHP Basics has 0 pages

Objects are handles

When you assign an object to another variable, PHP copies the handle, not the object. Both variables then point at the same object. Use clone when you need a separate copy:

php · try it yourself
<?php
class Counter {
    public int $value = 0;
}

$a = new Counter();
$b = $a;          // same object
$c = clone $a;    // independent copy

$a->value = 5;

echo "a: {$a->value}\n";
echo "b: {$b->value}\n";
echo "c: {$c->value}\n";
var_dump($a === $b, $a === $c);
a: 5
b: 5
c: 0
bool(true)
bool(false)

The === operator on objects checks whether two variables refer to the same instance; == checks whether two objects of the same class have equal properties.

Useful object functions

Function / operator What it does
$obj instanceof Lamp true if $obj is a Lamp (or subclass)
get_class($obj) / $obj::class The class name as a string
property_exists($obj, 'color') Whether the class declares that property
method_exists($obj, 'toggle') Whether the method exists
get_object_vars($obj) Accessible properties as an array
php · try it yourself
<?php
class Point {
    public int $x = 0;
    public int $y = 0;

    public function moveBy(int $dx, int $dy): static {
        $this->x += $dx;
        $this->y += $dy;
        return $this;   // returning $this allows chaining
    }
}

$p = new Point();
$p->moveBy(2, 3)->moveBy(1, -1);

echo $p::class . "\n";
var_dump($p instanceof Point);
print_r(get_object_vars($p));
Point
bool(true)
Array
(
    [x] => 3
    [y] => 2
)

Returning $this from a method, as moveBy() does, lets you chain calls one after another.

Note: Since PHP 8.4 you can call a method directly on a freshly created object without extra parentheses: new Point()->moveBy(1, 1). Older versions required (new Point())->moveBy(1, 1).

Tip: Writing to a property that the class never declared creates a dynamic property, which is deprecated since PHP 8.2. Always declare your properties.

Test yourself

Inside a method, how do you read the object's name property?

  1. $name
  2. this.name
  3. $this->name
  4. $this->$name

After $b = $a; where $a is an object, what happens when you change $b->value?

  1. Only $b changes
  2. $a changes too, because both refer to the same object
  3. PHP throws an error
  4. A clone is made automatically

What happens when you read a typed property that was never assigned and has no default?

  1. It returns null
  2. It returns an empty string
  3. An Error is thrown
  4. A notice is printed and 0 is returned