codecamp

PHP8 Stringable 接口

(PHP 8)

简介

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

它的主要价值是能让函数针对简单的字符串或可以转化为字符串的对象,检测联合类型 string|Stringable。

接口摘要

class 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

目录

  • Stringable::__toString — 从对象中获取字符串表示


PHP8 WeakMap 类
PHP8 UnitEnum 接口
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定