
Stringable 인터페이스는 PHP 8.0 버전부터 제공되는 인터페이스입니다. 이 인터페이스를 구현하여 __toString() 메소드를 오버라이딩하는 방법은 다음과 같습니다.
1. Stringable 인터페이스를 구현하는 클래스를 생성합니다.
#hostingforum.kr
php
class MyStringable implements Stringable
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function __toString(): string
{
return $this->value;
}
}
2. __toString() 메소드를 오버라이딩하여 정의된 문자열을 반환합니다. 위 예시에서는 $value 프로퍼티의 값을 반환합니다.
3. 오버라이딩한 __toString() 메소드를 호출하여 결과를 확인합니다.
#hostingforum.kr
php
$myStringable = new MyStringable('Hello, World!');
echo $myStringable . "n"; // Hello, World!
Stringable 인터페이스를 구현하여 __toString() 메소드를 오버라이딩하면, 해당 클래스의 인스턴스는 문자열과 유사하게 사용할 수 있습니다.
2025-07-14 12:09