[nycphp-talk] multiple object instantiations in a single script
Dan Cech
dcech at phpwerx.net
Sat Oct 9 07:57:48 EDT 2004
Matthew Terenzio wrote:
> What a weird subject line. Is it an OOP or procedural question?
>
> What I mean is. . .
>
> Well, suppose you have a User class and a register() function in the
> class.
>
> Then on a given script/page you are looping through some values and you
> want to create a new User and register it every time through the loop.
> Of course it doesn't work because you can't do something like:
>
> $name = new User;
>
> more than once.
Actually, this will work just fine.
> 1) Do most people use dynamically named variables?
Very rarely, it's generally clearer to use an array if you want to keep
the variable for later, or just unset/reuse it.
ie:
$users = array();
foreach ($signups as $id => $signup) {
$users[$id] = new User();
$users[$id]->register();
}
or:
foreach ($signups as $signup) {
$user = new User();
$user->register();
unset($user);
}
the call to unset is optional, if you leave it out the variable $user
will be overwritten on each iteration through the loop.
Dan
More information about the talk
mailing list