I’d like to reuse a functionality several times in a single class. This functionality relies on a private variable:
trait Address {
private $address;
public function getAddress() {
return $this->address;
}
public function setAddress($address) {
$this->address = $address;
}
}
The only way I’ve found to use the trait twice, is the following:
class User {
use Address {
getAddress as getHomeAddress;
setAddress as setHomeAddress;
getAddress as getWorkAddress;
setAddress as setWorkAddress;
}
}
The problem is, by doing this, the private variable $address is shared across the different methods, and the code will not work as expected:
$user = new User();
$user->setHomeAddress('21 Jump Street');
echo $user->getWorkAddress(); // 21 Jump Street
Is there a solution to really use the trait twice, while not sharing its private variables?
Declaring a trait with
usewill not create an instance of that trait. Traits are basically just code that is copy and pasted into the using class. Theaswill only create an Alias for that method, e.g. it will add something liketo your User class. But it will still only be that one trait. There will not be two different
$addressproperties, but just one.You could make the methods private and then delegate any public calls to it via
__callby switch/casing on the method name and using an array for address, e.g.But that is just a can of worms.
In other words, you cannot sanely do what you are trying to do with traits. Either use two different traits. Or use good old aggregation and add concrete proxy methods.