这是我在方法链接时发现的一个有趣的怪癖,我很难绕过它。我确定有解决方案或其他方式。这很难解释,但我会尽力而为。
例子:
您拥有三个属于类的函数,以及如下 2 个受保护的属性。
class Chain {
protected $_str = '';
protected $_part = 0;
public function __toString() {
return implode(' ', $this->_str);
}
public function AAA () {
$this->_str[$this->_part] = 'AAA';
$this->_part++;
return $this;
}
public function BBB () {
$this->_str[$this->_part] = 'BBB';
$this->_part++;
return $this;
}
public function wrap ($str) {
$part = $this->_part - 1;
$this->_str[$part] = "({$str})";
return $this;
}
}
现在,当链接这些方法,特别是使用 wrap 方法时,先前链中的字符串会无意中附加。例子:
$chain = new Chain();
$chain->AAA()->BBB()->wrap($chain->AAA());
echo $chain;
您期望字符串的样子是AAA BBB (AAA)
.
但是,实际返回的是AAA BBB (AAA BBB AAA)
.
Why is it that wrap()
takes all the previous methods called within the chain instead of only the method that's actually wrapped by it? What is the best way around this assuming there is one?