Home  >  Article  >  Backend Development  >  对象的深拷贝有没有什么高效的做法?

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

WBOY
WBOYOriginal
2016-06-06 20:21:391109browse

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

<code>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;
    }
}
</code>

回复内容:

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

<code>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;
    }
}
</code>

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:mysql 连接出错Next article:java - PHP soap 调用