PHP 的 流畅字符串

等级 5284 次按键

使用返回$this的流畅方法链式处理字符串操作。

PHP 代码

// 方法会修改字符串并返回$this的包装类
1class S {
// 提升的public属性$v保存字符串
2 public function __construct(
3 public string $v
4 ) {}
5
// 转换为大写
6 public function upper(): static {
7 $this->v = strtoupper($this->v);
// 返回$this使方法可以链式调用
8 return $this;
9 }
10
// 去掉首尾空白
11 public function trim(): static {
12 $this->v = trim($this->v);
13 return $this;
14 }
15}
16
// 首尾带空格的字符串
17$s = new S(" Hello World ");
// 先trim再upper,然后读取$v:输出HELLO WORLD
18echo $s->trim()->upper()->v;

运行结果

HELLO WORLD
用这段代码练习打字

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

这段代码中的符号

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

  • $× 9
  • (× 8
  • )× 8
  • -× 7
  • >× 7
  • ;× 6
  • {× 4
  • }× 4
  • =× 3
  • _× 2

PHP 等级 5 的更多代码示例

← 返回 PHP 打字练习