PHP __get和__set魔术方法 [英] PHP __get and __set magic methods
问题描述
除非我完全误解,否则应该使用__get
和__set
方法重载→get
和set
.
Unless I'm completely mistaken, the __get
and __set
methods are supposed to allow overloading of the → get
and set
.
例如,以下语句应调用__get
方法:
For example, the following statements should invoke the __get
method:
echo $foo->bar;
$var = $foo->bar;
并且以下应使用__set
方法:
$foo->bar = 'test';
这在我的代码中不起作用,并且可以通过以下简单示例重现:
This was not working in my code, and is reproducible with this simple example:
class foo {
public $bar;
public function __get($name) {
echo "Get:$name";
return $this->$name;
}
public function __set($name, $value) {
echo "Set:$name to $value";
$this->$name = $value;
}
}
$foo = new foo();
echo $foo->bar;
$foo->bar = 'test';
echo "[$foo->bar]";
这只会导致:
[test]
在其中放置一些die()
呼叫表明它根本没有击中它.
Putting some die()
calls in there shows that it is not hitting it at all.
现在,我只是说了一下要拧紧它,并在目前需要的地方手动使用__get
,但这不是很动态,并且需要知道重载"的代码实际上是不会被调用的,除非专门调用.我想知道这是不是应该按照我了解的方式起作用,或者为什么它不能起作用.
For now, I just said screw it, and am manually using __get
where it's needed for now, but that's not very dynamic and requires knowledge that the 'overloaded' code is in fact not being called unless specifically called. I'd like to know if this is either not supposed to function the way I've understood that it should or why this is not working.
它在php 5.3.3
上运行.
推荐答案
__get
,__set
,__call
和__callStatic
.您的$bar
是公开的,因此无法访问.
__get
, __set
, __call
and __callStatic
are invoked when the method or property is inaccessible. Your $bar
is public and therefor not inaccessible.
将数据写入不可访问的属性时,将运行
__set()
.__get()
用于从不可访问的属性读取数据.
__set()
is run when writing data to inaccessible properties.__get()
is utilized for reading data from inaccessible properties.
魔术方法不能替代吸气剂和吸气剂.它们只允许您处理方法调用或属性访问,否则将导致错误.因此,还有更多与错误处理相关的信息.另外请注意,它们比使用正确的getter和setter或直接方法调用要慢得多.
The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.
这篇关于PHP __get和__set魔术方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!