【问题标题】:In PHP, can I alias a class property? E.g. to allow ArrayAccess methods via Trait在 PHP 中,我可以为类属性设置别名吗?例如。允许通过 Trait 使用 ArrayAccess 方法
【发布时间】: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'];

【问题讨论】:

    标签: php traits


    【解决方案1】:

    如果您在 trait 中定义私有属性,那么您可能不应该在实现它的类中直接引用它们。相反,只需使用 trait 中的方法。即,而不是在具体类中这样做:

    $this->container["one"] = 1;
    

    这样做:

    $this["one"] = 1;
    

    那么你就不需要知道storage属性叫什么,也不需要围绕设置/获取它编写任何代码。另请注意,您不需要在类中重新定义 private $container = [];,因为它已经带有 trait。

    【讨论】:

    • 这完全有道理——我会这样做的。感谢负载!! :D
    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 2015-04-17
    • 2014-01-29
    • 2010-11-24
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多