Stringable 接口

(PHP 8)

简介

Stringable 接口表示拥有 __toString() 方法的类。 和大多数接口不同, Stringable 隐式存在于任何定义了 __toString() 魔术方法的类上, 当然也可以显式声明它,并且推荐这么做。

它的主要价值是能让函数针对简单的字符串或可以转化为字符串的对象,检测联合类型 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) {
// 通过在此处调用 __toString,Stringable 将会获得转化后的字符串
print $value;
}

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

showStuff($ip);
?>

以上例程的输出类似于:

123.234.42.9

目录

add a note

User Contributed Notes 1 note

up
24
Gormack
1 year 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