将所有对象属性复制到此

将所有对象属性复制到此

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

问题描述

我有一个 PHP 对象,类型为 MyObject.

I have an object in PHP, of the type MyObject.

$myObject instanceof MyObject

现在,在 class MyObject 中,有一个非静态函数,在那里,我使用对me"的引用,例如 $this,但是我那里还有另一个对象.

Now, in the class MyObject, there is a non-static function, and in there, I use the reference to "me", like $this, but I also have another object there.

是否有可能在不执行 $this = $myObject 的情况下实现或多或少相同的效果,例如 set_object_vars($this, get_object_vars($myObject))?

Is it possible, without doing $this = $myObject, to achieve more or less the same effect, like something of the sort set_object_vars($this, get_object_vars($myObject))?

推荐答案

<?php

class MyObject
{
    public function import(MyObject $object)
    {
        foreach (get_object_vars($object) as $key => $value) {
            $this->$key = $value;
        }
    }
}

我猜会做你想做的事,但你应该注意以下几点:

Will do what you want I guess, but you should be aware of the following:

  1. get_object_vars 只会找到非静态属性
  2. get_object_vars 只会根据范围
  3. 找到可访问的属性
  1. get_object_vars will only find non-static properties
  2. get_object_vars will only find accessible properties according to scope

根据范围 部分非常重要,可能需要多解释一下.您是否知道 PHP 中的属性范围是类相关而不是实例相关的?

The according to scope part is quite important and may deserve a little more explanation. Did you know that properties scope are class dependent rather than instance dependent in PHP?

这意味着在上面的例子中,如果你在 MyObject 中有一个 private $bar 属性,get_object_vars 会看到它,因为你位于 MyObject 类的实例中.如果您尝试导入另一个类的实例,这显然不起作用.

It means that in the example above, if you had a private $bar property in MyObject, get_object_vars would see it, since you are in an instance of a MyObject class. This will obviously not work if you're trying to import instances of another class.

这篇关于PHP 将所有对象属性复制到此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:06