python魔力的PHP方法

2024-05-16 15:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 方法利用路由属性面向风格mongo密钥
2条回答

您应该看看PHP的神奇方法:http://php.net/manual/en/language.oop5.magic.php

__get()__set()和{}可以做你想做的事。在

看看__get() and __set()和{a2}。在

使用前者,您可以使非公共成员可访问,如$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  

始终如一,正如你所要求的。在

相关问题 更多 >