我想在一个类中多次重用一个功能。此功能依赖于私有变量:
trait Address {
private $address;
public function getAddress() {
return $this->address;
}
public function setAddress($address) {
$this->address = $address;
}
}
我发现使用 trait 两次的唯一方法是:
class User {
use Address {
getAddress as getHomeAddress;
setAddress as setHomeAddress;
getAddress as getWorkAddress;
setAddress as setWorkAddress;
}
}
问题是,通过这样做,私有变量$address
在不同的方法之间共享,并且代码将无法按预期工作:
$user = new User();
$user->setHomeAddress('21 Jump Street');
echo $user->getWorkAddress(); // 21 Jump Street
有没有真正使用该特征两次而不共享其私有变量的解决方案?