PHP 的 魔术方法 __toString

等级 4165 次按键

定义 __toString,使对象可以当作字符串使用;对该对象执行 echo 输出“Color: Red”。

PHP 代码

1class Color {
// 构造函数属性提升声明 private 属性 $name
2 public function __construct(
3 private string $name
4 ) {}
5
// 每当对象被当作字符串使用时,PHP 会调用 __toString
6 public function __toString(): string {
7 return "Color: $this->name";
8 }
9}
10
// echo 通过 __toString 转换对象,输出“Color: Red”
11echo new Color("Red");

运行结果

Color: Red
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 PHP 代码中需要输入的符号及其出现次数。

  • _× 4
  • "× 4
  • (× 3
  • )× 3
  • {× 3
  • }× 3
  • ;× 2
  • :× 2
  • $× 2
  • -× 1

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习