Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP copy all object properties to this

Tags:

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

$myObject instanceof MyObject

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.

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))?

like image 996
arik Avatar asked Jan 03 '12 13:01

arik


People also ask

When an object is cloned PHP will perform copy of all subject properties?

When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

What is object cloning in PHP?

PHP has clone keyword that creates a shallow copy of the object. However, if original object has other embedded object as one of its properties, the copied object still refers to the same. To create a eep copy of object, the magic method __clone() needs to be defined in the class/


2 Answers

<?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 will only find non-static properties
  2. get_object_vars will only find accessible properties according to scope

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?

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.

like image 126
Geoffrey Bachelet Avatar answered Oct 10 '22 04:10

Geoffrey Bachelet


@Geoffrey Bachelet we can improve this:

class MyObject
{
    //object or array as parameter
    public function import($object)
    {   
        $vars=is_object($object)?get_object_vars($object):$object;
        if(!is_array($vars)) throw Exception('no props to import into the object!');
        foreach ($vars as $key => $value) {
            $this->$key = $value;
        }
    }   
}

The difference is here that you can pass an ordinary array (hashtable) as well as an object. Think in example about some data coming from the database.

like image 38
Nadir Avatar answered Oct 10 '22 04:10

Nadir