22

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
arik
  • 28,170
  • 36
  • 100
  • 156
  • What do you mean "*use the reference to 'me', like `$this`*", are you aliasing `$this` in the method? – Dan Lugg Jan 03 '12 at 13:13
  • I think your question needs a little review. Even if we had a set_object_vars() function would that be really the same effect? You would be copying the object, not referencing it. See copying vs referencing in PHP for more. – Slavic Jan 03 '12 at 13:14
  • Your question doesn't make much sense to me. _'I use the reference to "me", like `$this`'_ - especially. Maybe this is what your looking for, maybe it is not: [PHP Clone class](http://php.net/manual/en/language.oop5.cloning.php) – George Reith Jan 03 '12 at 13:22
  • Sorry for confusing you. I did not need the same reference, only the properties had to be the same. – arik Jan 03 '12 at 14:59

2 Answers2

67
<?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.

Geoffrey Bachelet
  • 4,047
  • 2
  • 21
  • 17
  • Thanks! Didn't think if that! Now, I only need to copy the properties to the instance, the static properties are irrelevant ^^ – arik Jan 03 '12 at 14:58
1

@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.

Nadir
  • 695
  • 8
  • 12