Statement on glibc/iconv Vulnerability

Stringable インターフェイス

(PHP 8)

はじめに

Stringable インターフェイスは、 特定のクラスが __toString() メソッドを実装していることを示します。 ほとんどのインターフェイスと異なり、 Stringable は、マジックメソッド __toString() が定義されているあらゆるクラスで 暗黙のうちに存在すると見なされますが、 明示的に宣言することもできますし、宣言すべきです。

このインターフェイスの一番の存在意義は、 文字列プリミティブや、 文字列にキャストできるオブジェクトを受け入れる union型 string|Stringable に対する型チェックを、関数ができるようにすることです。

インターフェイス概要

interface Stringable {
/* メソッド */
public __toString(): string
}

Stringable インターフェイスの例

例1 基本的な Stringable インターフェイスの使い方

<?php
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) {
// Stringable の場合、__toString をコールすることで
// オブジェクトが文字列に変換されます。
print $value;
}

$ip = new IPv4Address('123', '234', '42', '9');

showStuff($ip);
?>

上の例の出力は、 たとえば以下のようになります。

123.234.42.9

目次

add a note

User Contributed Notes 1 note

up
33
Gormack
2 years ago
Since it's introduced in PHP 8, IPv4Address class Example #1 could be shortened to:
<?php
class IPv4Address implements Stringable {
public function
__construct(private string $oct1, private string $oct2, private string $oct3, private string $oct4) {
}

public function
__toString(): string {
return
"$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}
?>
To Top