动态地将私有属性添加到对象

动态地将私有属性添加到对象

本文介绍了动态地将私有属性添加到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

class Foo {
    // Accept an assoc array and appends its indexes to the object as property
    public function extend($values){
        foreach($values as $var=>$value){
            if(!isset($this->$var))
                $this->$var = $value;
        }
    }
}

$Foo = new Foo;
$Foo->extend(array('name' => 'Bee'));

现在$Foo对象具有值为Bee的公共name属性.

Now the $Foo object has a public name property with value Bee.

如何更改extend函数以使变量私有?

How to change extend function to make variables private ?

修改使用私有数组是另一种方法,绝对不是我的答案.

EditUsing a private array is another way and definitely not my answer.

推荐答案

简单,糟糕的设计.

在运行时添加私有[!]字段的目的是什么?现有的方法不能依赖于这样添加的字段,并且您会弄乱对象的功能.

What's the purpose of adding a private [!] field at runtime? Existent methods can't rely on such added fields, and you'd be messing with the object functionality.

如果您希望对象的行为类似于哈希图[即您可以只调用$obj -> newField = $newValue],考虑使用魔术__get__set方法.

If you want your object to behave like an hashmap [i.e. you can just call $obj -> newField = $newValue], consider using magic __get and __set methods.

这篇关于动态地将私有属性添加到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:46