Perl6 Object Oriented Cookbook (v0.2.1)  
Section 1: Introduction to Object Oriented Perl6  
 
Recipe 1.11: Using Classes as Objects
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

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

How acceptable is the proposed solution?
  (Login to Vote)
5.00 Rating, 4 Votes  

Problem:  

You want to use a class as if it were an object.

Solution:  

You can't. What you probably meant to do was make a new object, and use that:

my $obj = MyClass.new;   # create a new object of type "MyClass"
$obj.foo();              # do something with the resulting object

MyClass.foo();           # WRONG, if foo is not a class method

Discussion:

In the last recipe, we noted that object instances could be used as classes, in the sense that you could call class methods on objects and expect it to Do The Right Thing.

The inverse is not true. If you're calling an instance method on a class name, you're probably doing something wrong, because there is no "object" for the method to operate on. Calling an instance method via a class name therefore causes an exception.

Keep in mind that a class is merely a definition of what it means to be an object of a certain type; it doesn't actually create an object, unless and until you ask for one to be created.


Log In to Comment


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