PHP:我可以在方法重载(__get)中获得数组功能吗?

DS_*_*per 0 php arrays overloading get

我想要实现的是当我打电话给$ obj-> CAT [15]; $ obj会检查属性CAT是否存在,如果没有,请立即获取值

public function __get($var){
if($var == "CAT") return $this->cats->get_cat($cat_id);
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是......如何从我的例子中得到数组的值15?将它传递给我的get_cat方法?

Ion*_*tan 6

__get返回一个实例ArrayAccess,将委托给get_catoffsetGet的方法.

像这样的东西:

class CachedCategories implements ArrayAccess
{
  private $memcachedClient;

  public function __construct($memcachedClient)
  {
    $this->memcachedClient = $memcachedClient;
  }

  // Called when using `$cats[18] = "foo"`
  public function offsetSet($key, $value)
  {
    $this->memcachedClient->set($key, $value);
  }

  // Called when using `$cat = $cats[18]`
  public function offsetGet($key)
  {
    return $this->memcachedClient->get($key);
  }

  // Called when using `isset($cats[18])`
  public function offsetExists($key)
  {
    return $this->memcachedClient->get($key) !== false;
  }

  // Called when using `unset($cats)`
  public function offsetUnset($key)
  {
    $this->memcachedClient->delete($key);
  }
}

$cats = new CachedCategories($someMemcachedClient);
$cats[18];
Run Code Online (Sandbox Code Playgroud)