Re: Copying an Object

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



You could create a method of class B that takes an object of class A as a
parameter and copies each property line by line (or method of class A that
takes an object of class B...).  If you don't want to add a method you could
just do the same thing, but procedurally.  The issue with this (aside from
being bad oop) is that you can't copy private properties unless you have all
the required getters and setters.  The issue with both of these is that it's
ugly, high maintenance code.

There is the iterator class, extending from which would allow you iterate
through all of your properties in a foreach, but if you don't want to add a
new method then you likely don't want to add a parent class.

I don't care for any of these options, but as far as I know there's no
internal PHP mechanism to to copy all the properties from one object to
another object of a different class - please correct me if I'm wrong.  Is it
possible that there's a more elegant solution to your problem that does not
include a mass copy of all an object's properties? (e.g. using statics like
Mr Bungle suggested or perhaps some nifty design pattern?)


Chris H.




On Wed, Sep 22, 2010 at 7:35 AM, Daniel Kolbo <kolb0057@xxxxxxx> wrote:

> Hello PHPers,
>
> I have:
>
> class A {
>        ...code
> }
>
> class B extends A {
>        ...code
> }
>
> $a = new A();
>
> $b = new B();
>
> I would like to get all of the properties of $a into $b by value.  Class
> A extends 3 other classes.  I would like a way to not have to manage a
> 'copy' method in B if A or one of the subclasses of A change.
>
> I was reading about clone, but this doesn't really seem to help me in
> this situation.
>
> How can I copy $a into $b?
>
> Thanks,
> dK
> `
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux