Stringable 接口

(PHP 8)

簡介

Stringable 接口表示擁有 __toString() 方法的類。 和大多數(shù)接口不同, Stringable 隱式存在于任何定義了 __toString() 魔術(shù)方法的類上, 當然也可以顯式聲明它,并且推薦這么做。

它的主要價值是能讓函數(shù)針對簡單的字符串或可以轉(zhuǎn)化為字符串的對象,檢測聯(lián)合類型 string|Stringable。

接口摘要

interface Stringable {
/* 方法 */
public __toString(): string
}

Stringable 示例

示例 #1 基礎(chǔ) 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) {
    
// 通過在此處調(diào)用 __toString,Stringable 將會獲得轉(zhuǎn)化后的字符串
    
print $value;
}

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

showStuff($ip);
?>

以上例程的輸出類似于:

123.234.42.9

目錄