TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   Object Association doubt. (http://www.talkphp.com/advanced-php-programming/4787-object-association-doubt.html)

sohdubom 07-27-2009 04:58 PM

Object Association doubt.
 
Hi. I was wondering which one of the samples below would be right to set as object association.

===snippet 01===
PHP Code:

$p1 = new Person(10'John Doe''31/07/1967');
$a1 = new Account;
$a1->accountOwner $p1;
var_dump($a1);
unset(
$a1);
echo isset(
$p1) ? '$p1 isset' '$p1 is not set'// Person is still set 

=============

===snippet 02===
PHP Code:

$a1 = new Account;
$a1->accountOwner = new Person(10'John Doe''31/07/1967');
var_dump($a1);
unset(
$a1);
// both Account and Person are unset here 

=============

In snippet 01 objects Person and Account are created separately and then I reference assign Person to Account, $a1->accountOwner = $p1;

In snippet 02 I reference assign Person to Account, $a1->accountOwner = new Person(10, 'John Doe', '31/07/1967'); so that I don't have $p1 explicitly assigned.

The doubt is: which one is considered to be Association?

Thanx in advance :-)

wGEric 07-27-2009 08:13 PM

Neither of those are passing a variable by reference.

In snippet 1, $p1 is being copied into $a1->accountOwner. Both variables have their own location within the memory. Put an & in front of the variable and both variables will be using the same location in memory making $a1->accountOwner and $p1 essentially the same whereas before they were two different objects in memory.

PHP Code:

$p1->name 'John';
$a1->accountOwner = &$p1;

$a1->accountOwner->name 'Bob';
echo 
$p1->name// returns 'Bob' 


Salathe 07-27-2009 08:17 PM

Eric, for PHP 5 and onwards that's simply not true. Objects are assigned by reference; if you wish to assign a copy then use the clone keyword.

sohdubom 07-27-2009 08:41 PM

Yes, we don't need the & in PHP5 ... but actually snippet 01 and 02 are not regular Association, but instead the specialized versions: Agregattion and Composition


All times are GMT. The time now is 05:31 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0