PHP 8 中的 Stringable 接口是什么?
phpserver side programmingprogramming更新于 2025/10/8 23:52:17
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 接口使传递字符串变得非常简单。当类实现 __toString 方法时,会自动添加 Stringable 接口。无需显式实现该接口。当强制使用严格类型 (string_types=1) 时,Stringable 接口有助于进行类型提示。
示例:在 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)

