4

OBS:我直接在这里编码,因为我的代码要复杂得多。

如果我编码:

class SuperFoo {
    public function __get($name) {
        return $this->$name;
    }
    public function __set($name, $value) {
        $this->$name = $value;
    }
}

class Foo extends SuperFoo {
    private $bar = '';
}

$foo = new Foo();
$foo->bar = "Why it doesn't work?";
var_dump($foo);

结果是:

object(Foo) {
    ["bar":"Foo":private]=> 
        string(0) ''
}

而不是:

object(Foo) {
    ["bar":"Foo":private]=> 
        string(20) 'Why it doesn't work?'
}

为什么会这样?我不想使用数组来保存属性,因为我需要将它们声明为单独的私有成员。

4

3 回答 3

5

您的代码应该会导致致命错误,因为您正在尝试访问私有属性。即使在此之前,您也应该收到语法错误,因为您没有正确声明您的函数。因此,您“导致” var dump 永远不会发生。

编辑:

你已经编辑了你的问题。它不起作用的原因是因为bar是私有的FooSuperFoo无法访问它)。protected代替它。

于 2013-04-15T16:20:30.127 回答
2

__get($name) 如果 object 具有称为的属性,则不会调用$name它,但它会尝试直接使用该属性。而且您的属性是私有的,因此是错误的。

__set() 在将数据写入不可访问的属性时运行。

__get() 用于从不可访问的属性中读取数据。

于 2013-04-15T16:20:13.237 回答
1

If Foo::bar is private, Foo needs to override __get and __set. This is because SuperFoo can't access private members of Foo. The following code works but it's ugly:

class SuperFoo {
    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }
}

class Foo extends SuperFoo {
    private $bar = '';

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }
}

The proper solution is to modify Foo::bar visibility to protected. Now SuperFoo has access to Foo::bar so there's no need to override __get and __set in Foo.

class SuperFoo {
    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }
}

class Foo extends SuperFoo {
    protected $bar = '';
}

Check out the PHP Documentation on visibility

于 2014-12-17T22:51:08.527 回答