PHP 8에서 새로운 Stringable 인터페이스 (__toSting) 추가됩니다. 이 메서드는 이중 밑줄(__)로 시작합니다. __toString 메서드를 사용하면 문자열로 표시된 개체를 가져올 수 있습니다. 클래스가 __toString을 사용하여 메서드를 정의하는 경우 , 문자열로 처리해야 할 때마다 개체를 호출합니다.
예:__toString을 사용한 Stringable 인터페이스
<?php
class Employee{
public function __toString(): string
{
return 'Employee Name';
}
}
$employee = new Employee();
print_r((string)$employee);
?> 출력
Employee Name
PHP 8에서 Stringable 인터페이스를 사용하면 문자열을 쉽게 전달할 수 있습니다. Stringable 인터페이스 클래스가 __toString을 구현하면 자동으로 추가됩니다. 방법. 인터페이스를 명시적으로 구현할 필요는 없습니다. Stringable 인터페이스는 엄격한 유형이 부과될 때마다 유형 힌트에 유용할 수 있습니다. (string_types=1) .
예:PHP 8에서 Stringable 인터페이스 사용
<?php
declare(strict_types=1);
class Employee {
public function __toString() {
return 'Employee Details';
}
}
$emp = new Employee;
var_dump($emp instanceof Stringable);
?> 출력
bool(true)