当前位置:Gxlcms > PHP教程 > 对象的深拷贝有没有什么高效的做法?

对象的深拷贝有没有什么高效的做法?

时间:2021-07-01 10:21:17 帮助过:3人阅读

clone对象的时候使用深拷贝有没有什么通用且高效的方法?
现在我的做法是用反射类去遍历,但只是一层的,这样做的话是不是对象内的对象依旧是引用的?
那么有没有人能提供一下多层深拷贝的做法呢?

public function __clone()
{
    $reflectClass = new \ReflectionClass(__CLASS__);
    foreach ($reflectClass->getProperties() as $properity)
    {
        $name = $properity-> name;
        if (\is_object($this->$name))
            $this->$name = clone $this->$name;
    }
}

回复内容:

clone对象的时候使用深拷贝有没有什么通用且高效的方法?
现在我的做法是用反射类去遍历,但只是一层的,这样做的话是不是对象内的对象依旧是引用的?
那么有没有人能提供一下多层深拷贝的做法呢?

public function __clone()
{
    $reflectClass = new \ReflectionClass(__CLASS__);
    foreach ($reflectClass->getProperties() as $properity)
    {
        $name = $properity-> name;
        if (\is_object($this->$name))
            $this->$name = clone $this->$name;
    }
}

不需要用到的反射的呀,单个对象只需要关心自己的属性里又哪些是需要深拷贝的,直接调用 clone 拷贝即可,至于那个对象又是如何处理他的深拷贝的,应该交给他自己去处理。

人气教程排行