略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Stringable

2024-04-28

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 $oct1string $oct2string $oct3string $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 noteadd a note

User Contributed Notes 1 note

up
9
Gormack
7 months 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";
    }
}
?>

官方地址:https://www.php.net/manual/en/class.stringable.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3