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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?