Perl6 Object Oriented Cookbook (v0.2.1)  
Section 2: Attributes and Methods  
 
Recipe 2.4: Creating 'Class Attributes'
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
5.00 Rating, 4 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
2.50 Rating, 2 Votes  

Problem:  

You want to create an attribute that is the same for all instances of a class: instead of each instance of a class having a separate copy of the attribute, each instance should instead refer to one, "classwide" value.

Solution:  

Use my and our:

class MyClass {
    my  $bar = 0;
    our $foo = 0;
    
    method zap { ... }
}

Discussion:

Perl6 classes are simply special types of packages; you can use my and our as you would inside a normal package. my declares a variable that is private to the class it is created in. our declares a variable that is publicly available.

Issue: There's a problem with this, if we want to allow MyClass.foo to work (as opposed to $MyClass::foo): another recipe states that calling-by-classname would circumvent privacy, meaning you couldn't have private class attribs.


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page