如何在 PHP 中链接方法?
phpserver side programmingprogramming更新于 2025/4/17 22:52:17
可以使用 mutator 方法链接方法,其中这些方法返回原始对象,并且可以在这些由 mutator 函数返回的对象上调用其他方法。
示例
下面是一个简单的示例,演示了相同的操作 −
<?php
class sample_class {
private $str;
function __construct() {
$this->str = "";
}
function addA() {
$this->str .= "am";
return $this;
}
function addB() {
$this->str .= "_bn";
return $this;
}
function getStr() {
return $this->str;
}
}
$new_object = new sample_class();
echo $new_object->addA()->addB()->getStr();
输出
这将产生以下输出 −
am_bn

