douhui7136 2011-01-17 13:30
浏览 45
已采纳

PHP __get和__set魔术方法

Unless I'm completely mistaken, the __get and __set methods are supposed to allow overloading of the → get and set.

For example, the following statements should invoke the __get method:

echo $foo->bar;
$var = $foo->bar;

And the following should use the __set method:

$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]";

This only results in:

[test]

Putting some die() calls in there shows that it is not hitting it at all.

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.

This is running on php 5.3.3.

  • 写回答

8条回答 默认 最新

  • drs3925 2011-01-17 13:34
    关注

    __get, __set, __call and __callStatic are invoked when the method or property is inaccessible. Your $bar is public and therefor not inaccessible.

    See the section on Property Overloading in the manual:

    • __set() is run when writing data to inaccessible properties.
    • __get() is utilized for reading data from inaccessible properties.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大