簡體   English   中英

PHP 5.3和接口\\ ArrayAccess

[英]PHP 5.3 and interface \ArrayAccess

我現在正在一個項目上,並且有一個實現ArrayAccess接口的類。

Howewer,出現一個錯誤,提示我的實現:

必須與ArrayAccess :: offsetSet()兼容。

我的實現如下所示:

public function offsetSet($offset, $value) {
  if (!is_string($offset)) {
    throw new \LogicException("...");
  }
  $this->params[$offset] = $value;
}

因此,在我看來,我的實現是正確的。 知道有什么問題嗎? 非常感謝!

該類如下所示:

class HttpRequest implements \ArrayAccess {
  // tons of private variables, methods for working
  // with current http request etc. Really nothing that
  // could interfere with that interface.

  // ArrayAccess implementation

  public function offsetExists($offset) {
    return isset ($this->params[$offset]);
  }

  public function offsetGet($offset) {
    return isset ($this->params[$offset]) ? $this->params[$offset] : NULL;
  }

  public function offsetSet($offset, $value) {
     if (!is_string($offset)) {
      throw new \LogicException("You can only assing to params using specified key.");
     }
     $this->params[$offset] = $value;
  }

  public function offsetUnset($offset) {
    unset ($this->params[$offset]);
  }
}

該類如下所示:

class HttpRequest implements \ArrayAccess {
  // tons of private variables, methods for working
  // with current http request etc. Really nothing that
  // could interfere with that interface.

  // ArrayAccess implementation

  public function offsetExists($offset) {
    return isset ($this->params[$offset]);
  }

  public function offsetGet($offset) {
    return isset ($this->params[$offset]) ? $this->params[$offset] : NULL;
  }

  public function offsetSet($offset, $value) {
     if (!is_string($offset)) {
      throw new \LogicException("You can only assing to params using specified key.");
     }
     $this->params[$offset] = $value;
  }

  public function offsetUnset($offset) {
    unset ($this->params[$offset]);
  }
}

在我看來,您的namespace或文件頂部的use指令使它查找與之兼容的錯誤ArrayAccess接口。 雖然沒有這些指令也無法確定。

一般來說:

您自己的名稱空間不應以反斜杠開頭或結尾:

使用: namespace Web\\Http;

不要 使用類似以下內容的 namespace \\Web\\Http; namespace \\Web\\Http; namespace \\Web\\Http\\;

對於文件中引用的每個類和接口,請添加一個use指令:

namespace MyProject;

use MyLibrary\BaseClass; // note no backslash before the namespace name
use \ArrayAccess;
use \Iterator;
use \Countable;

class MyClass extends BaseClass implements ArrayAccess, Iterator, Countable
{
    /* Your implementation goes here as normal */
}

在這里唯一引起我注意的是:

 public function offsetGet($offset) {
    return isset ($this->params[$offset]) ? $this->params[$offset] : NULL;
  }

也許將其替換為:

 public function offsetGet($offset) {
    return (isset ($this->params[$offset]) ? $this->params[$offset] : NULL);
  }

會完成技巧。

這也可能是語法錯誤,它會從您尚未粘貼的部分代碼中拖延下來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM