source: trunk/essentials/dev-lang/perl/pod/perlobj.pod@ 3368

Last change on this file since 3368 was 3181, checked in by bird, 19 years ago

perl 5.8.8

File size: 21.6 KB
Line 
1=head1 NAME
2X<object> X<OOP>
3
4perlobj - Perl objects
5
6=head1 DESCRIPTION
7
8First you need to understand what references are in Perl.
9See L<perlref> for that. Second, if you still find the following
10reference work too complicated, a tutorial on object-oriented programming
11in Perl can be found in L<perltoot> and L<perltooc>.
12
13If you're still with us, then
14here are three very simple definitions that you should find reassuring.
15
16=over 4
17
18=item 1.
19
20An object is simply a reference that happens to know which class it
21belongs to.
22
23=item 2.
24
25A class is simply a package that happens to provide methods to deal
26with object references.
27
28=item 3.
29
30A method is simply a subroutine that expects an object reference (or
31a package name, for class methods) as the first argument.
32
33=back
34
35We'll cover these points now in more depth.
36
37=head2 An Object is Simply a Reference
38X<object> X<bless> X<constructor> X<new>
39
40Unlike say C++, Perl doesn't provide any special syntax for
41constructors. A constructor is merely a subroutine that returns a
42reference to something "blessed" into a class, generally the
43class that the subroutine is defined in. Here is a typical
44constructor:
45
46 package Critter;
47 sub new { bless {} }
48
49That word C<new> isn't special. You could have written
50a construct this way, too:
51
52 package Critter;
53 sub spawn { bless {} }
54
55This might even be preferable, because the C++ programmers won't
56be tricked into thinking that C<new> works in Perl as it does in C++.
57It doesn't. We recommend that you name your constructors whatever
58makes sense in the context of the problem you're solving. For example,
59constructors in the Tk extension to Perl are named after the widgets
60they create.
61
62One thing that's different about Perl constructors compared with those in
63C++ is that in Perl, they have to allocate their own memory. (The other
64things is that they don't automatically call overridden base-class
65constructors.) The C<{}> allocates an anonymous hash containing no
66key/value pairs, and returns it The bless() takes that reference and
67tells the object it references that it's now a Critter, and returns
68the reference. This is for convenience, because the referenced object
69itself knows that it has been blessed, and the reference to it could
70have been returned directly, like this:
71
72 sub new {
73 my $self = {};
74 bless $self;
75 return $self;
76 }
77
78You often see such a thing in more complicated constructors
79that wish to call methods in the class as part of the construction:
80
81 sub new {
82 my $self = {};
83 bless $self;
84 $self->initialize();
85 return $self;
86 }
87
88If you care about inheritance (and you should; see
89L<perlmodlib/"Modules: Creation, Use, and Abuse">),
90then you want to use the two-arg form of bless
91so that your constructors may be inherited:
92
93 sub new {
94 my $class = shift;
95 my $self = {};
96 bless $self, $class;
97 $self->initialize();
98 return $self;
99 }
100
101Or if you expect people to call not just C<< CLASS->new() >> but also
102C<< $obj->new() >>, then use something like the following. (Note that using
103this to call new() on an instance does not automatically perform any
104copying. If you want a shallow or deep copy of an object, you'll have to
105specifically allow for that.) The initialize() method used will be of
106whatever $class we blessed the object into:
107
108 sub new {
109 my $this = shift;
110 my $class = ref($this) || $this;
111 my $self = {};
112 bless $self, $class;
113 $self->initialize();
114 return $self;
115 }
116
117Within the class package, the methods will typically deal with the
118reference as an ordinary reference. Outside the class package,
119the reference is generally treated as an opaque value that may
120be accessed only through the class's methods.
121
122Although a constructor can in theory re-bless a referenced object
123currently belonging to another class, this is almost certainly going
124to get you into trouble. The new class is responsible for all
125cleanup later. The previous blessing is forgotten, as an object
126may belong to only one class at a time. (Although of course it's
127free to inherit methods from many classes.) If you find yourself
128having to do this, the parent class is probably misbehaving, though.
129
130A clarification: Perl objects are blessed. References are not. Objects
131know which package they belong to. References do not. The bless()
132function uses the reference to find the object. Consider
133the following example:
134
135 $a = {};
136 $b = $a;
137 bless $a, BLAH;
138 print "\$b is a ", ref($b), "\n";
139
140This reports $b as being a BLAH, so obviously bless()
141operated on the object and not on the reference.
142
143=head2 A Class is Simply a Package
144X<class> X<package> X<@ISA> X<inheritance>
145
146Unlike say C++, Perl doesn't provide any special syntax for class
147definitions. You use a package as a class by putting method
148definitions into the class.
149
150There is a special array within each package called @ISA, which says
151where else to look for a method if you can't find it in the current
152package. This is how Perl implements inheritance. Each element of the
153@ISA array is just the name of another package that happens to be a
154class package. The classes are searched (depth first) for missing
155methods in the order that they occur in @ISA. The classes accessible
156through @ISA are known as base classes of the current class.
157
158All classes implicitly inherit from class C<UNIVERSAL> as their
159last base class. Several commonly used methods are automatically
160supplied in the UNIVERSAL class; see L<"Default UNIVERSAL methods"> for
161more details.
162X<UNIVERSAL> X<base class> X<class, base>
163
164If a missing method is found in a base class, it is cached
165in the current class for efficiency. Changing @ISA or defining new
166subroutines invalidates the cache and causes Perl to do the lookup again.
167
168If neither the current class, its named base classes, nor the UNIVERSAL
169class contains the requested method, these three places are searched
170all over again, this time looking for a method named AUTOLOAD(). If an
171AUTOLOAD is found, this method is called on behalf of the missing method,
172setting the package global $AUTOLOAD to be the fully qualified name of
173the method that was intended to be called.
174X<AUTOLOAD>
175
176If none of that works, Perl finally gives up and complains.
177
178If you want to stop the AUTOLOAD inheritance say simply
179X<AUTOLOAD>
180
181 sub AUTOLOAD;
182
183and the call will die using the name of the sub being called.
184
185Perl classes do method inheritance only. Data inheritance is left up
186to the class itself. By and large, this is not a problem in Perl,
187because most classes model the attributes of their object using an
188anonymous hash, which serves as its own little namespace to be carved up
189by the various classes that might want to do something with the object.
190The only problem with this is that you can't sure that you aren't using
191a piece of the hash that isn't already used. A reasonable workaround
192is to prepend your fieldname in the hash with the package name.
193X<inheritance, method> X<inheritance, data>
194
195 sub bump {
196 my $self = shift;
197 $self->{ __PACKAGE__ . ".count"}++;
198 }
199
200=head2 A Method is Simply a Subroutine
201X<method>
202
203Unlike say C++, Perl doesn't provide any special syntax for method
204definition. (It does provide a little syntax for method invocation
205though. More on that later.) A method expects its first argument
206to be the object (reference) or package (string) it is being invoked
207on. There are two ways of calling methods, which we'll call class
208methods and instance methods.
209
210A class method expects a class name as the first argument. It
211provides functionality for the class as a whole, not for any
212individual object belonging to the class. Constructors are often
213class methods, but see L<perltoot> and L<perltooc> for alternatives.
214Many class methods simply ignore their first argument, because they
215already know what package they're in and don't care what package
216they were invoked via. (These aren't necessarily the same, because
217class methods follow the inheritance tree just like ordinary instance
218methods.) Another typical use for class methods is to look up an
219object by name:
220
221 sub find {
222 my ($class, $name) = @_;
223 $objtable{$name};
224 }
225
226An instance method expects an object reference as its first argument.
227Typically it shifts the first argument into a "self" or "this" variable,
228and then uses that as an ordinary reference.
229
230 sub display {
231 my $self = shift;
232 my @keys = @_ ? @_ : sort keys %$self;
233 foreach $key (@keys) {
234 print "\t$key => $self->{$key}\n";
235 }
236 }
237
238=head2 Method Invocation
239X<invocation> X<method> X<arrow> X<< -> >>
240
241For various historical and other reasons, Perl offers two equivalent
242ways to write a method call. The simpler and more common way is to use
243the arrow notation:
244
245 my $fred = Critter->find("Fred");
246 $fred->display("Height", "Weight");
247
248You should already be familiar with the use of the C<< -> >> operator with
249references. In fact, since C<$fred> above is a reference to an object,
250you could think of the method call as just another form of
251dereferencing.
252
253Whatever is on the left side of the arrow, whether a reference or a
254class name, is passed to the method subroutine as its first argument.
255So the above code is mostly equivalent to:
256
257 my $fred = Critter::find("Critter", "Fred");
258 Critter::display($fred, "Height", "Weight");
259
260How does Perl know which package the subroutine is in? By looking at
261the left side of the arrow, which must be either a package name or a
262reference to an object, i.e. something that has been blessed to a
263package. Either way, that's the package where Perl starts looking. If
264that package has no subroutine with that name, Perl starts looking for
265it in any base classes of that package, and so on.
266
267If you need to, you I<can> force Perl to start looking in some other package:
268
269 my $barney = MyCritter->Critter::find("Barney");
270 $barney->Critter::display("Height", "Weight");
271
272Here C<MyCritter> is presumably a subclass of C<Critter> that defines
273its own versions of find() and display(). We haven't specified what
274those methods do, but that doesn't matter above since we've forced Perl
275to start looking for the subroutines in C<Critter>.
276
277As a special case of the above, you may use the C<SUPER> pseudo-class to
278tell Perl to start looking for the method in the packages named in the
279current class's C<@ISA> list.
280X<SUPER>
281
282 package MyCritter;
283 use base 'Critter'; # sets @MyCritter::ISA = ('Critter');
284
285 sub display {
286 my ($self, @args) = @_;
287 $self->SUPER::display("Name", @args);
288 }
289
290It is important to note that C<SUPER> refers to the superclass(es) of the
291I<current package> and not to the superclass(es) of the object. Also, the
292C<SUPER> pseudo-class can only currently be used as a modifier to a method
293name, but not in any of the other ways that class names are normally used,
294eg:
295X<SUPER>
296
297 something->SUPER::method(...); # OK
298 SUPER::method(...); # WRONG
299 SUPER->method(...); # WRONG
300
301Instead of a class name or an object reference, you can also use any
302expression that returns either of those on the left side of the arrow.
303So the following statement is valid:
304
305 Critter->find("Fred")->display("Height", "Weight");
306
307and so is the following:
308
309 my $fred = (reverse "rettirC")->find(reverse "derF");
310
311The right side of the arrow typically is the method name, but a simple
312scalar variable containing either the method name or a subroutine
313reference can also be used.
314
315=head2 Indirect Object Syntax
316X<indirect object syntax> X<invocation, indirect> X<indirect>
317
318The other way to invoke a method is by using the so-called "indirect
319object" notation. This syntax was available in Perl 4 long before
320objects were introduced, and is still used with filehandles like this:
321
322 print STDERR "help!!!\n";
323
324The same syntax can be used to call either object or class methods.
325
326 my $fred = find Critter "Fred";
327 display $fred "Height", "Weight";
328
329Notice that there is no comma between the object or class name and the
330parameters. This is how Perl can tell you want an indirect method call
331instead of an ordinary subroutine call.
332
333But what if there are no arguments? In that case, Perl must guess what
334you want. Even worse, it must make that guess I<at compile time>.
335Usually Perl gets it right, but when it doesn't you get a function
336call compiled as a method, or vice versa. This can introduce subtle bugs
337that are hard to detect.
338
339For example, a call to a method C<new> in indirect notation -- as C++
340programmers are wont to make -- can be miscompiled into a subroutine
341call if there's already a C<new> function in scope. You'd end up
342calling the current package's C<new> as a subroutine, rather than the
343desired class's method. The compiler tries to cheat by remembering
344bareword C<require>s, but the grief when it messes up just isn't worth the
345years of debugging it will take you to track down such subtle bugs.
346
347There is another problem with this syntax: the indirect object is
348limited to a name, a scalar variable, or a block, because it would have
349to do too much lookahead otherwise, just like any other postfix
350dereference in the language. (These are the same quirky rules as are
351used for the filehandle slot in functions like C<print> and C<printf>.)
352This can lead to horribly confusing precedence problems, as in these
353next two lines:
354
355 move $obj->{FIELD}; # probably wrong!
356 move $ary[$i]; # probably wrong!
357
358Those actually parse as the very surprising:
359
360 $obj->move->{FIELD}; # Well, lookee here
361 $ary->move([$i]); # Didn't expect this one, eh?
362
363Rather than what you might have expected:
364
365 $obj->{FIELD}->move(); # You should be so lucky.
366 $ary[$i]->move; # Yeah, sure.
367
368To get the correct behavior with indirect object syntax, you would have
369to use a block around the indirect object:
370
371 move {$obj->{FIELD}};
372 move {$ary[$i]};
373
374Even then, you still have the same potential problem if there happens to
375be a function named C<move> in the current package. B<The C<< -> >>
376notation suffers from neither of these disturbing ambiguities, so we
377recommend you use it exclusively.> However, you may still end up having
378to read code using the indirect object notation, so it's important to be
379familiar with it.
380
381=head2 Default UNIVERSAL methods
382X<UNIVERSAL>
383
384The C<UNIVERSAL> package automatically contains the following methods that
385are inherited by all other classes:
386
387=over 4
388
389=item isa(CLASS)
390X<isa>
391
392C<isa> returns I<true> if its object is blessed into a subclass of C<CLASS>
393
394You can also call C<UNIVERSAL::isa> as a subroutine with two arguments. Of
395course, this will do the wrong thing if someone has overridden C<isa> in a
396class, so don't do it.
397
398If you need to determine whether you've received a valid invocant, use the
399C<blessed> function from L<Scalar::Util>:
400X<invocant> X<blessed>
401
402 if (blessed($ref) && $ref->isa( 'Some::Class')) {
403 # ...
404 }
405
406C<blessed> returns the name of the package the argument has been