6.5 Private and Public

     

By default, all methods and attribute accessors are public methods, so they can be called anywhere . You can also declare private methods or accessors, which can be called only within the class where they're defined, or from certain trusted classes. A private method is declared with a colon at the start of the name :

 method :inaccessible ($self: $value) { . . . } 

A private attribute is declared with a colon in place of the dot (.) in the name:

 has $:hidden; 

You call a private method or accessor with a colon in the call:

 $object.:hidden(42); 

The attribute variable ( $:name or $.name ) is never accessible outside the class, whether the attribute is public or private.

At first glance this might look like nothing more than the "encapsulation by convention" of Perl 5. It's actually much more than that. The colon implicitly sets a private trait on the method or attribute. The encapsulation is enforced by the interpreter. An external call to a private method will fail as if the method simply didn't exist. External queries to the package symbol table for private methods also fail.

Only public methods are inherited by a derived class, but inherited public methods can call private methods from their own class. Private methods and attributes in a role are private to the composed class, as if they were defined in that class.

The one loophole in private methods is that a class can declare that it trusts certain other classes to allow those classes to access its private methods. Roles cannot declare a trusted class. In this example, the Friendly class declares that it trusts the Zaphod class:

 class Friendly {     trusts Zaphod; # probably a bad idea, really } 



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net