Stringable 介面

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

目錄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *