在观看Symfony源码的时候,发现了这种写法$this['logger'] = $value $this 是个对象。纳尼,对象也能这么玩,然后我赶紧就试了一下,然后,显而易见,挂掉了。原来,之所以能够当作数组来用是因为,实现了PHP的一个叫做ArrayAccess 接口,随手写了一个示例。 接口说明::提供像访问数组一样访问对象的能力的接口。

    1. <?php
    2. class base implements ArrayAccess {
    3. protected $values;
    4. protected $keys;
    5. /**
    6. * Whether a offset exists
    7. * @link http://php.net/manual/en/arrayaccess.offsetexists.php
    8. * @param mixed $offset <p>
    9. * An offset to check for.
    10. * </p>
    11. * @return boolean true on success or false on failure.
    12. * </p>
    13. * <p>
    14. * The return value will be casted to boolean if non-boolean was returned.
    15. * @since 5.0.0
    16. */
    17. public function offsetExists($offset){
    18. return isset($this->keys[$offset]);
    19. }
    20. /**
    21. * Offset to retrieve
    22. * @link http://php.net/manual/en/arrayaccess.offsetget.php
    23. * @param mixed $offset <p>
    24. * The offset to retrieve.
    25. * </p>
    26. * @return mixed Can return all value types.
    27. * @since 5.0.0
    28. */
    29. public function offsetGet($offset){
    30. return $this->values[$offset];
    31. }
    32. /**
    33. * Offset to set
    34. * @link http://php.net/manual/en/arrayaccess.offsetset.php
    35. * @param mixed $offset <p>
    36. * The offset to assign the value to.
    37. * </p>
    38. * @param mixed $value <p>
    39. * The value to set.
    40. * </p>
    41. * @return void
    42. * @since 5.0.0
    43. */
    44. public function offsetSet($offset, $value){
    45. $this->values[$offset] = $value;
    46. }
    47. /**
    48. * Offset to unset
    49. * @link http://php.net/manual/en/arrayaccess.offsetunset.php
    50. * @param mixed $offset <p>
    51. * The offset to unset.
    52. * </p>
    53. * @return void
    54. * @since 5.0.0
    55. */
    56. public function offsetUnset($offset){
    57. unset($this->values[$offset]);
    58. }
    59. }
    60. class im extends base{
    61. public function addAttr($key, $value){
    62. $this[$key] = $value;
    63. $this->keys[] =$key;
    64. }
    65. public function showAttr(){
    66. return array_combine($this->keys, $this->values);
    67. }
    68. }
    69. echo '
    70. <pre>';
    71. $im = new im();
    72. $im->addAttr('name', 'zhangsan');
    73. $im->addAttr('addr', 'Shanghai');
    74. $res = $im->showAttr();
    75. echo $im['name'];
    76. var_dump($im);