class a {
protected $_a,$_b,$_c;
public function b(string $_v) {
$this->_a = $_v;
return $this;
}
public function c(string $_v) {
$this->_b = $_v;
return $this;
}
public function d(string $_v) {
$this->_c = $_v;
return $this;
}
public function print() {
return ($this->_a .' '. $this->_b .' '. $this->_c);
}
}
$a = new a();
echo $a->b('bbb')->c('ccc')->d($a->b('111')->c('222')->d('333')->print())->print();
理论输出 :bbb ccc 111 222 333
实际输出:111 222 111 222 333
请教如何不重新new对象和static的前提解决变量污染?
感谢
使用 clone ,如果你后续还需要用到这个对象,那就单独给一个变量
$b
来保存其次,这个不能叫污染,因为你自始至终都是操作的
$a
这一个对象实例,是符合预期的。需要注意的是
如果你的属性是对象,就需要深拷贝,考虑使用 deep-copy