#development #php

PHP reminder: you can use the method __toString() to specify the string representation of an object. Don't forget to implement the interface Stringable to make it work.

 1class IPv4Address implements Stringable {
 2    private string $oct1;
 3    private string $oct2;
 4    private string $oct3;
 5    private string $oct4;
 6
 7    public function __construct(string $oct1, string $oct2, string $oct3, string $oct4) {
 8        $this->oct1 = $oct1;
 9        $this->oct2 = $oct2;
10        $this->oct3 = $oct3;
11        $this->oct4 = $oct4;
12    }
13
14    public function __toString(): string {
15        return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";
16    }
17}
18
19function showStuff(string|Stringable $value) {
20    // A Stringable will get converted to a string here by calling
21    // __toString.
22    print $value;
23}
24
25$ip = new IPv4Address('123', '234', '42', '9');
26
27showStuff($ip);

From the documentation:

The Stringable interface denotes a class as having a __toString() method. Unlike most interfaces, Stringable is implicitly present on any class that has the magic __toString() method defined, although it can and should be declared explicitly.

Its primary value is to allow functions to type check against the union type string|Stringable to accept either a string primitive or an object that can be cast to a string.