4

我想知道 PHP 中是否有某种方法可以复制 Python 属性/键访问的一些魔力。

我使用了一个由Steve Lacey编写的名为Minimongo的 Mongo ORM 类,他在其中利用__getattr__and__getitem__来重新路由键和属性风格的访问,并保留 Mongo 的“面向文档”的性质。 val = doc.fooval = doc['foo']变得等价。

我想知道 PHP 中是否有类似的接口,它允许更改从它继承的类的对象访问处理方式。我翻遍了 STL,找不到适合的。这对于设置默认值非常有用。谢谢。

4

2 回答 2

9

看看__get() 和 __set()ArrayAccess

使用前者,您可以让非公共成员访问,如$obj->foo,使用后者,您可以访问它们,如$obj['foo'].

您可以在内部随意硬连线它们。

就个人而言,我建议您将这些可神奇访问的属性保存在该类的一个数组成员中,这样您就不会得到意大利面条式代码。

POC:

 1  <?php
 2  class Magic implements ArrayAccess {
 3  
 4      protected $items = array();
 5  
 6      public function offsetExists($key) {
 7          return isset($this->items[$key]);
 8      }
 9      public function offsetGet($key) {
10          return $this->items[$key];
11      }
12      public function offsetSet($key, $value) {
13          $this->items[$key] = $value;
14      }
15      public function offsetUnset($key) {
16          unset($this->items[$key]);
17      }
18  
19      //do not modify below, this makes sure we have a consistent
20      //implementation only by using ArrayAccess-specific methods
21      public function __get($key) {
22          return $this->offsetGet($key);
23      }
24      public function __set($key, $value) {
25          $this->offsetSet($key, $value);
26      }
27      public function __isset($key) {
28          return $this->offsetExists($key);
29      }
30      public function __unset($key) {
31          $this->offsetUnset($key);
32      }
33  }
34  
35  //demonstrate the rountrip of magic
36  $foo = new Magic;
37  $foo['bar'] = 42;
38  echo $foo->bar, PHP_EOL;//output 42
39  $foo->bar++;
40  echo $foo['bar'];//output 43
41  

一致性大人,正如您所问。

于 2012-01-04T21:43:29.210 回答
2

你应该看看 PHP 的魔法方法:http: //php.net/manual/en/language.oop5.magic.php

__get()__set()并且__call()可以为所欲为。

于 2012-01-04T21:42:34.063 回答