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


PHP: Can I get array functionality in method overloading (__get)?

我想要实现的是,当我调用$obj->CAT[15];$obj将检查属性CAT是否存在,如果不存在,则动态获取值

public function __get($var){
if($var == "CAT") return $this->cats->get_cat($cat_id);
}
我的问题是……如何从我的例子中获得数组的值15 ?传递给我的get_cat方法?

__get返回一个ArrayAccess的实例,该实例将在其offsetGet方法中委托给get_cat

像这样:

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];

class Test
{
    protected $cats;
    function __construct()
    {
        $this->cats = new ArrayObject(); // or your own implementation
        $this->cats[33] = "hey";
    }
    public function __get($name)
    {
        if($name == "CAT") return $this->cats;
    }
}
$a = new Test();
echo $a->CAT[33];

参见http://www.php.net/ArrayAccess实现你自己的list/map

希望这对你有帮助!

如果我正确理解了您想要实现的目标,您可以使用闭包:

class kittengarten
{
   var $cats;
   function __construct()
   {
      $this->cats[0]='Jerry';
      $this->cats[1]='John';
      $this->cats[2]='Barack';
   }
   public function __get($var)
   {
      if($var == "CAT")
      {
         $array_of_cats=$this->cats;
         return function($num) use ($array_of_cats)
         {
            return $array_of_cats[$num];
         };
      }
   }
}
$kittengarten=new kittengarten();
echo 'The third directly accessed cat is '.$kittengarten->cats[2];
$cat=$kittengarten->CAT;
if (is_string($cat)) echo $kittengarten->CAT; 
else echo 'The third cat accessed using closure is '.$cat(2);
输出:

第三个直接访问的cat是Barack

使用闭包访问的第三个cat是Barack