Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
The stupid question is the question not asked
 
PerlMonks  

How can I create private object variables?

by premchai21 (Curate)
on Mar 17, 2001 at 19:08 UTC ( [id://65181]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

premchai21 has asked for the wisdom of the Perl Monks concerning the following question: (object-oriented programming)

How can I create private object variables?

Originally posted as a Categorized Question.

  • Comment on How can I create private object variables?

Replies are listed 'Best First'.
Re: How can I create private object variables?
by jeffa (Bishop) on Mar 17, 2001 at 20:33 UTC

    Use closures. Check out perltoot for more info on how this code works.

    { package Foo; sub new { my $pkg = shift; my %data = ( bar => undef, ); bless sub { my $field = shift; @_ and $data{$field} = shift; $data{$field} }, $pkg } sub bar { my $self = shift; # the blessed closure $self->( 'bar', @_ ) } }
    And use:
    my $foo = new Foo; $foo->bar(42); # set it print $foo->bar; # get it
Re: How can I create private object variables?
by ton (Friar) on Apr 04, 2001 at 20:06 UTC
    ... but you usually don't need to. Since your source code is almost always accessible to the caller, s/he can easily modify it to read your members if s/he is determined. I prefer the more perl-y approach of indicating which variables are private via naming conventions (most people use a beginning underscore for private variables). This lets the user know that you make no guarentees about the existance of the member; e.g. the caller can access it if s/he wants to, but it might not be there in the next version. If their reliance on the existance of that member breaks their code later on, then it's their damn fault for accessing data that was not meant to be accessed. :)

    My $0.02

    Originally posted as a Categorized Answer.

Re: How can I create private object variables?
by pemungkah (Priest) on Nov 07, 2006 at 20:46 UTC

    Inside-out classes are another nice way to do this. The data is held in a my (lexical) variable inside the class; all the outside world sees is an anonymous scalar which is blessed into the class. The methods can access the class lexicals (as long as they're defined within scope of the lexicals), but the outside world can't.

    See Class::Std and Object::InsideOut for examples.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://65181]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.