| |
| Recipe 1.6: Instantiating Objects |
Last Updated: Sep 8, 2003
Status: Very Likely
|
|
|
|
How important is this problem to you?
(Login to Vote)
4.80 Rating, 5 Votes
|
|
How acceptable is the proposed solution?
(Login to Vote)
4.17 Rating, 6 Votes
|
|
Problem:
   
Now that you've declared your class, you want to instantiate it; that is, to make objects of that type.
Solution:
  
Use code like:
my $obj = MyClass.new(...); # (1) OK
my $obj = MyClass.new; # (2) OK, if new() takes no arguments
my MyClass $obj = MyClass.new(...); # (3) almost the same as (1), but more explicit
my MyClass $obj = MyClass.new; # (4) almost the same as (2), but more explicit
# my MyClass $obj .= new; # maybe a synonym for (4)
# my new MyClass $obj; # maybe a synonym for (4)
# my MyClass! $obj; # maybe a synonym for (4)
Discussion:
An object is explicitly created by calling its new method. You can leave out the parentheses, just as with any other Perl subroutine.
In each of the examples shown, we are explicitly creating the object, and placing it in the variable $obj. (1) and (2) place the new object into an untyped variable named $obj; (3) and (4) do the same, but give the variable $obj a required type, MyClass.
Issue:
One of the synonyms for (4) would be nice, since (4) is pretty wordy.
|
|