如何使变量私有于特征?
我想在单个类中多次重用一个功能。此功能依赖于私有变量:
trait Address {
private $address;
public function getAddress() {
return $this->address;
}
public function setAddress($address) {
$this->address = $address;
}
}
我发现两次使用该特征的唯一方法是:
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
有没有一个解决方案可以真正使用两次该特征,同时不共享其私有变量?