We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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.
class IPv4Address implements Stringable {
private string $oct1;
private string $oct2;
private string $oct3;
private string $oct4;
public function __construct(string $oct1, string $oct2, string $oct3, string $oct4) {
$this->oct1 = $oct1;
$this->oct2 = $oct2;
$this->oct3 = $oct3;
$this->oct4 = $oct4;
}
public function __toString(): string {
return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}
function showStuff(string|Stringable $value) {
// A Stringable will get converted to a string here by calling
// __toString.
print $value;
}
$ip = new IPv4Address('123', '234', '42', '9');
showStuff($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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.