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条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像