Classes and objects

PHP · Essentials · 14 min

Modern PHP code, and every framework, is organised into classes.

A class bundles data (properties) and behaviour (methods). Create an instance with new, and access members with ->. Inside a method, $this is the current object.

Constructor property promotion (PHP 8.0) declares and assigns properties straight from the constructor signature:

class Point {
    public function __construct(public int $x = 0, public int $y = 0) {}
}

Visibility controls access: public (anyone), protected (the class and subclasses), private (the class only). Keep properties private or protected and expose methods, or use readonly and property hooks, covered later.

Static members belong to the class instead of an instance: public static function create() is called as Point::create(), and constants are declared with const and read with self::NAME inside or Point::NAME outside.

Inheritance uses extends. A child can override a method and call the parent's version with parent::method(). Mark a class or method final to forbid overriding.

Objects are handles. Assigning an object to another variable or passing it to a function does not copy it: both names refer to the same object. Use clone $obj for a (shallow) copy. This is the opposite of arrays, which are copied by value.

Since PHP 8.4 you can call a method directly on new without extra parentheses: new Point(1, 2)->length().

Example

<?php
class Counter {
    private int $count = 0;
    public const STEP = 1;

    public function __construct(public readonly string $name) {}

    public function increment(): static {
        $this->count += self::STEP;
        return $this;              // allow chaining
    }

    public function value(): int { return $this->count; }
}

$a = new Counter('clicks');
$a->increment()->increment();
$b = $a;                 // same object, not a copy
$b->increment();
echo $a->name, ': ', $a->value(), "\n";   // clicks: 3

$c = clone $a;
$c->increment();
echo $a->value(), ' vs ', $c->value(), "\n";   // 3 vs 4

Remember

  • Constructor promotion declares and assigns properties in one place
  • Objects are passed as handles; use clone for a copy
  • Static members and constants are accessed with ::

Watch out for

  • Assuming passing an object to a function protects it from modification; the function can change it.

Check yourself

  1. After $b = $a; $b->count = 5; for an object $a, what is $a->count?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/language.oop5.decon.php