Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: OO doesn't seem to play nice with multiple instances

by diotalevi (Canon)
on Jun 01, 2005 at 21:08 UTC ( [id://462661]=note: print w/replies, xml ) Need Help??


in reply to OO doesn't seem to play nice with multiple instances

Store the name in the $this/$self object, not in the global $_name. $_name was a single variable shared between multiple objects and thus you were always overwriting the value whenever you called myNameIs.

package Interesting; sub new { my ( $class ) = @_; return bless {}, $class; } sub myNameIs{ my ( $self, $name ) = @_; defined $name or die "Don't tell me that I don't have a name."; # Store the name into the object return $self->{name} = $name; } sub whoAmI{ my ( $self ) = @_; # Retrieve the name from the object. return $self->{name}; }

Separately, I would like to urge you to stop using the syntax $one = new Interesting in favor of $one = Interesting->new. There are some tricky bugs related to the first syntax and you can avoid that entire class of errors by just not using that syntax. If there were a new() function in the same package as the code which had new Interesting, then instead of calling Interesting::new( 'Interesting' ) it would call WhateverPackage::new( 'Interesting' ). In OO code, if you had another class with a method named new(), then you might find that the incorrect new() method was being called.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://462661]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-16 17:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found