array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'class.stringable.php', 1 => 'Stringable', ), 'up' => array ( 0 => 'reserved.interfaces.php', 1 => '预定义接口和类', ), 'prev' => array ( 0 => 'weakmap.offsetunset.php', 1 => 'WeakMap::offsetUnset', ), 'next' => array ( 0 => 'stringable.tostring.php', 1 => 'Stringable::__toString', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'language/predefined/stringable.xml', ), 'extra_header_links' => array ( 'rel' => 'alternate', 'href' => '/manual/en/feeds/class.stringable.atom', 'type' => 'application/atom+xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 8)
Stringable 接口表示拥有 __toString() 方法的类。 和大多数接口不同, Stringable 隐式存在于任何定义了 __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