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

时间:2012-11-16 10:46:25

标签: php oop

我有一个班级:

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对象的公共name属性值为Bee

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

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

4 个答案:

答案 0 :(得分:3)

你可以这样做。

__get函数将检查是否在内部设置了给定的键 私有财产。

class Foo {

private $data = array();

// Accept an array and appends its indexes to the object as property
public function extend($values){
    foreach($values as $i=>$v){
        if(!isset($this->$i))
            $this->data[$i] = $v;
    }
}

public function __get($key) {
    if (isset($this->data[$key])) {
        return $this->data[$key];
    }
}

}

答案 1 :(得分:3)

简单,糟糕的设计。

在运行时添加私有[!]字段的目的是什么?现有的方法不能依赖于这些添加的字段,而且你会搞乱对象的功能。

如果您希望对象的行为类似于散列图[即你可以致电$obj -> newField = $newValue],考虑使用魔术__get__set方法。

答案 2 :(得分:0)

我会使用整个数组:

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

class Foo {
    private $options = array();

    public function setOptions(array $options) {
        $this->options = $options;
    }

    public function getOption($value = false) {
        if($value) {
            return $this->options[$value];    
        } else {
            return $this->options;
        }
    }
}

然后在需要其他值时有更多选项,您可以遍历数组并使用它们。当你在大多数情况下有一个变量时,它有点复杂。

答案 3 :(得分:0)

这是一种基于访问者的方法:

class Extendible
{
    private $properties;

    public function extend(array $properties)
    {
        foreach ($properties as $name => $value) {
            $this->properties[$name] = $value;
        }
    }

    public function __call($method, $parameters)
    {
        $accessor = substr($method, 0, 3);
        $property = lcfirst(substr($method, 3));
        if (($accessor !== 'get' && $accessor !== 'set')
                || !isset($this->properties[$property])) {
            throw new Exception('No such method!');
        }
        switch ($accessor) {
            case 'get':
                return $this->getProperty($property);
                break;
            case 'set':
                return $this->setProperty($property, $parameters[0]);
                break;
        }
    }

    private function getProperty($name)
    {
        return $this->properties[$name];
    }

    private function setProperty($name, $value)
    {
        $this->properties[$name] = $value;
        return $this;
    }
}

演示:

try {
    $x = new Extendible();
    $x->extend(array('foo' => 'bar'));
    echo $x->getFoo(), PHP_EOL; // Shows 'bar'
    $x->setFoo('baz');
    echo $x->getFoo(), PHP_EOL; // Shows 'baz'
    echo $x->getQuux(), PHP_EOL; // Throws Exception
} catch (Exception $e) {
    echo 'Error: ', $e->getMessage(), PHP_EOL;
}