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

问题描述

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

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

$myObject instanceof MyObject

现在,在class MyObject中,有一个非静态函数,并且在其中,我像$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属性,由于您位于MyObject类的实例中,因此get_object_vars会看到它.如果您要尝试导入另一个类的实例,这显然将不起作用.

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将所有对象属性复制到此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 21:38