Determine if object instance is same reference or clone.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Determine if object instance is same reference or clone.

Post by jmut »

I am using php5.

How could I determine if an instantiated object is the same or a clone.

Example:

Singleton pattern will create/return THE SAME instance of an object.

Factory pattern will create/return ANOTHER instance of an object.


How could I find out that this is trully so -- without testing with some internal(object) properties etc....and see if they change.....
Is there a function for this.

Like for example there is is_a to check if an object is from a given class.
Thanks.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Not sure if comparing the serialized objects would do that for you?
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

d11wtq wrote:Not sure if comparing the serialized objects would do that for you?
I don't think either.
It's a memory issue as far as I know. I need if both objects take same memorry allocation.
Grr, will have to test object properties to see if they are the same. :(
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

PHP Manual wrote: When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Weirdan wrote:
PHP Manual wrote: When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
So then:

Code: Select all

class myClass
{
    //
}

$foo = new myClass();

$bar = &$foo;

if ($foo === $bar) echo 'Yes';
else echo 'No';
Behaves differently to:

Code: Select all

$foo = new myClass();

$bar = new myClass();

if ($foo === $bar) echo 'Yes';
else echo 'No';
Actually I'll have a play around to test... :)
Post Reply