doutou6803 2014-01-21 17:50
浏览 42
已采纳

更新存储为私有属性的对象的属性时,为什么不激活PHP __set()魔术方法?

Given the following design pattern...

class Person
{
    private $properties = array(); // will eventually hold an address object

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

    public function __get($name)
    {
        if (!empty($this->properties[$name])) {
            return $this->properties[$name];
        }
    }
}

// create a generic object to hold address data
$home_address = new stdClass();
$home_address->postal = '12345';

// instantiate a new person object and assign $home_address as property
$customer = new Person;
// __set() magic method fires just fine
$customer->home_address = $home_address;

// now try to set a property of the address object
// __set() magic method DOES NOT fire
$customer->home_address->country = 'USA';

// best work around i can find is to assign the current
// address to a temporary variable and then re-assign
// it back to the property
$temp_address = $customer->home_address;
$temp_address->country = 'USA';
// __set() magic method fires just fine
$customer->home_address = $temp_address;

Why doesn't the __set() method fire when I add / update a property (for example, country) on the private property of home_address directly?

The only work around I have found is to use a temporary variable and completely overwrite the address private property in order to fire the __set() method.

Any best practice advice or am I not understanding the best way to use the __set() method here?

  • 写回答

4条回答 默认 最新

  • dpd2349 2014-01-21 17:56
    关注

    I don't think you are looking at this correctly.

    When you try to set $customer->home_address->country, you are trying to set a property on the stdClass() object that is set to home_addresss property of $customer. This would in no way invoke a setter on $customer.

    Your initial setting of home_address does in invoke the __set() magic method as home_address is not defined as a property on Person class.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?