问题描述
我想知道PHP中是否有某种方法可以复制Python属性/键访问的某些魔术.
I was wondering if there was some way in PHP to duplicate some of the magic of Python attribute/key access.
我使用由史蒂夫·莱西(Steve Lacey)编写的Mongo ORM类,称为 Minimongo ,他利用__getattr__
和__getitem__
重新路由键和属性风味的访问,并保留Mongo的面向文档"的性质. val = doc.foo
和val = doc['foo']
等效.
I use a Mongo ORM class written by Steve Lacey called Minimongo in which he utilizes the __getattr__
and __getitem__
to reroute key and attribute flavored access and preserve the 'document-oriented' nature of Mongo. val = doc.foo
and val = doc['foo']
become equivalent.
我想知道PHP中是否有类似的接口,该接口允许更改从其继承的类处理对象访问的方式.我查看了STL,找不到适合的衣服.设置默认值将非常有用.谢谢.
I was wondering if there is a similar interface in PHP that would allow the changing of how object access is handled for a class that inherits from it. I looked through the STL and couldn't find one that filled suit. It would be greatly useful for setting up defaults. Thanks.
推荐答案
看看 __ get()和__set()和 ArrayAccess .
使用前者,您可以使非公共成员可以访问,就像$obj->foo
一样;使用前者,您可以像$obj['foo']
一样访问它们.
With the former you can make non-public members accessbile, as in $obj->foo
, with the latter you can access them like $obj['foo']
.
您可以根据需要在内部对其进行硬接线.
You can hardwire them however you like, internally.
我个人建议您将这些可魔术访问的属性保留在类的单个数组成员中,这样您就不会得到意粉代码了.
Personally I would suggest you keep these magically-accessible properties into one single array member of the class, so you don't end up with spaghetti code.
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
Milord的一致性,完全按照您的要求.
Consistency Milord, exactly as you asked.
这篇关于PHP解决Python魔术__getattr __()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!