【发布时间】:2021-01-23 16:54:36
【问题描述】:
我在我的一些类中实现了ArrayAccess,而且我经常在我的类中使用与Example #1 on the ArrayAccess docs 中的ArrayAccess 方法几乎完全相同的代码。
由于代码是相同的,最好将其编写一次作为 Trait,然后我的类可以只使用 implement ArrayAccess(就像现在一样)和 use ArrayAccessTrait,而无需复制一堆 ArrayAccess 方法。
唯一能阻止这种情况的是,我通常不希望我的底层数组名为 $container,而是与我正在构建的类更相关的其他东西。
所以我的问题是,有没有办法“别名”我在自己的类中使用的任何数组属性名称,$container 在我的ArrayAccessTrait 中使用?
下面的例子有一个Foo 类,它显示了我想要的;此示例有效,但我希望能够在 Foo 类中使用名为 $container 以外的属性。
trait ArrayAccessTrait {
private $container = [];
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
class Foo implements ArrayAccess {
use ArrayAccessTrait;
private $container = [];
public function __construct() {
$this->container = [
"one" => 1,
"two" => 2,
"three" => 3,
];
}
public function hello($msg = 'Hello World') {
echo $msg . "<br/>\n";
}
}
$obj = new Foo;
$obj->hello();
echo "Array accessing element ['two'] = " . $obj['two'];
【问题讨论】: