为什么使用magic __set()方法无法直接访问数组?

时间:2011-08-25 13:53:48

标签: php oop

好的,所以这里是我的Properties基类的片段,在我的应用程序的大多数类中都有扩展:

class Properties {
    protected $properties_arr = array();

    /**
     * Magic function to be able to access the object's properties
     * @param string $property
     */
    public function __get( $property ) {
        if ( array_key_exists( $property, $this->properties_arr ) ) {
            return $this->properties_arr[ $property ];
        }

        return $this->getUndefinedProperty( $property );
    }

    /**
     * Magic function to be able to access the object's properties
     * @param string $property
     * @param mixed $value
     */
    public function __set( $property, $value ) {
        if ( property_exists( $this, $property ) ) {
            $this->setProtectedProperty( $property );
        }

        $this->properties_arr[ $property ] = $value;
    }

这是非常基本的,并且它没有任何问题,但我遇到了一个我以前遇到过的问题,而且你不能在array属性上执行某些操作通过__get方法。

这样做,例如:

$MyClass = new Properties();
$MyClass->test = array();
$MyClass->test['key'] = 'value';

你希望$MyClass->test数组包含一个项目,但它仍然是一个空数组!现在我知道我可以通过分配一个已包含在其中的项目的数组来解决它,但我真的很想知道为什么会这样(并且如果有更好的解决方案)。

谢谢!

2 个答案:

答案 0 :(得分:4)

请参阅PHP Accessor functions and arrays

问题可能是您需要使__get()方法返回引用。

答案 1 :(得分:0)

这是因为您还需要覆盖__isset魔术方法以检查数组索引是否存在。