It is useful that methods defined inside traits have an access to common scope of properties like methods defined in the same object. However is there any way that two traits could use the same property name but each of the property would be in a different scope so setTwo()
would not overwrite $this->data
of trait one
and vice-versa?
example:
<?php
namespace one;
trait one {
public function setOne($data) {
$this->data = $data;
}
public function getOne()
{
return $this->data;
}
}
namespace two;
trait two {
public function setTwo($data) {
$this->data = $data;
}
public function getTwo()
{
return $this->data;
}
}
namespace bar;
class Bar {
use \one\one;
use \two\two;
}
$bar = new Bar;
$bar->setOne(1);
$bar->setTwo(2);
echo "Bar getOne: " . $bar->getOne() . '<br>' . PHP_EOL; // echoes 2 instead of wanted 1
echo "Bar getTwo: " . $bar->getTwo() . '<br>' . PHP_EOL; // overwrites $this->data = 1 with 2
echo "Bar->data: " . $bar->data . '<br>' . PHP_EOL;
The reason why I'm looking for the separate scope is that for common properties' names like: sum, result, cache you may end up unintentionally overwriting them at some point when composing a class of many traits.
The only thing that comes to my mind is to use an intermediate class (that has it own namespace and by that its own scope) composed from traits and pass it as dependency to other class that needs some functionalities of the traits used for the intermediary composition. In the example as above I would need two intermediary classes - one with trait one, the other with trait two.
Are there any other options, besides the intermediate class or changing in every trait $this->data
to more custom names like $this->dataOne
and $this->dataTwo
?