Stringable interface
(PHP 8)
소개
Stringable 인터페이스는 __toString() 메서드가 있는 클래스를 나타냅니다. 대부분의 인터페이스와 달리 Stringable은 매직 __toString() 메서드가 정의된 모든 클래스에 암시적으로 존재하지만 명시적으로 선언할 수 있고 선언해야 합니다.
기본 값은 함수가 string|Stringable 조합 유형에 대해 유형 검사를 수행하여 문자열 프리미티브 또는 문자열로 캐스트할 수 있는 객체를 허용하도록 하는 것입니다.
인터페이스 개요
interface Stringable {
/* Methods */
public __toString(): string
}
Examples
예제 #1 기본 사용법
<?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) {
// 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
목차
- Stringable::__toString — Gets a string representation of the object