总有人间一两风,填我十万八千梦

PHP Stringable 用法 手册 | 示例代码

PHP开发手册 归档 152℃ 0评论

The Stringable interface

(PHP 8)

简介

The Stringable interface denotes a class as having a __toString() method. Unlike most interfaces, Stringable is implicitly present on any class that has the magic __toString() method defined, although it can and should be declared explicitly.

Its primary value is to allow functions to type check against the union type string Stringable to accept either a string primitive or an object that can be cast to a string.

类摘要

Stringable {
/* 方法 */

}

Stringable Examples

示例 #1 Basic Stringable Usage

<?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 
"$oct1.$oct2.$oct3.$oct4";
    }
}

function showStuff(string Stringable $value) {
    
// A Stringable will get converted to a string here by calling
    // __toString.
    
print $value;
}

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

showStuff($ip);
?>

以上例程的输出类似于:

123.234.42.9

用户贡献的笔记

There are no user contributed notes for this page.

转载请注明:悠然品鉴 » PHP Stringable 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址