基于PHP的内容克隆对象

时间:2014-06-08 20:07:41

标签: php object clone

我好像在这里绕圈子,但我有一种情况,我在阅读一些对象时,我可能会遇到一些包含数组的对象。当发生这种情况时,我希望基于数组生成新对象,例如

sourceObject(namespace\className)
    protected '_var1' => array('value1', 'value2')
    protected '_var2' => string 'variable 2'

应该成为

childObject1(namespace\className)
    protected '_var1' => string 'value1'
    protected '_var2' => string 'variable2'

childObject2(namespace\className)
    protected '_var1' => string 'value2'
    protected '_var2' => string 'variable2'

然而,由于不太了解我的克隆,我的克隆总是以相同的内容结尾(有时两者都是value1有时value2

1 个答案:

答案 0 :(得分:1)

您可以创建如下方法:

trait classSplitClone
{
    public function splitClone($name)
    {

        if (!is_array($this->$name)) {
            return [$this];
        }

        $objs   = [];
        $values = $this->$name;
        $c      = 0;
        foreach ($values as $value) {
            $objs[]          = $c ? clone $this : $this;
            $objs[$c]->$name = $value;
            $c++;
        }

        return $objs;
    }
}

然后在你的班级中使用它作为特征

class className
{
    use classSplitClone;

    protected $var1;
    protected $var2;

    function __construct($var1, $var2)
    {
        $this->var1 = $var1;
        $this->var2 = $var2;
    }
}

示例可能如下所示:

$obj = new className(['value1', 'value2'], 'variable 2');

print_r($obj->splitClone('var1'));

产生以下结果:

Array
(
    [0] => className Object
        (
            [var1:protected] => value1
            [var2:protected] => variable 2
        )

    [1] => className Object
        (
            [var1:protected] => value2
            [var2:protected] => variable 2
        )

)

希望这会有所帮助。您也可以通过ReflectionObject访问私人和受保护的成员。


完整示例代码(Demo):

<?php
/**
 * @link http://stackoverflow.com/a/24110513/367456
 */

/**
 * Class classSplitClone
 */
trait classSplitClone
{
    public function splitClone($name)
    {

        if (!is_array($this->$name)) {
            return [$this];
        }

        $objs   = [];
        $values = $this->$name;
        $c      = 0;
        foreach ($values as $value) {
            $objs[]          = $c ? clone $this : $this;
            $objs[$c]->$name = $value;
            $c++;
        }

        return $objs;
    }
}

/**
 * Class className
 */
class className
{
    use classSplitClone;

    protected $var1;
    protected $var2;

    function __construct($var1, $var2)
    {
        $this->var1 = $var1;
        $this->var2 = $var2;
    }
}

/*
 * Example
 */
$obj = new className(['value1', 'value2'], 'variable 2');

print_r($obj->splitClone('var1'));