xref: /openbsd-src/gnu/usr.bin/perl/pod/perlclass.pod (revision 5486feefcc8cb79b19e014ab332cc5dfd05b3b33)
1=head1 NAME
2
3perlclass - Perl class syntax reference
4
5=head1 SYNOPSIS
6
7    use v5.38;
8    use feature 'class';
9
10    class My::Example 1.234 {
11        field $x;
12
13        ADJUST {
14            $x = "Hello, world";
15        }
16
17        method print_message {
18            say $x;
19        }
20    }
21
22    My::Example->new->print_message;
23
24=head1 DESCRIPTION
25
26This document describes the syntax of Perl's C<class> feature, which provides
27native keywords for object-oriented programming.
28
29=head2 History
30
31Since Perl 5, support for objects revolved around the concept of I<blessing>
32references with a package name (see L<perlfunc/"bless REF,CLASSNAME">). Such a
33reference could then be used to call subroutines from the package it was
34blessed with (or any of its parents). This system, while bare-bones, was
35flexible enough to allow creation of multiple more advanced, community-driven
36systems for object orientation. For more information, see L<perlmod> and
37L<perlobj>.
38
39The C<class> feature is a core implementation of a class syntax that is similar
40to what one would find in other programming languages. It is not a wrapper
41around C<bless>, but a completely new system built right into the perl
42interpreter.
43
44=head1 KEYWORDS
45
46Enabling the C<class> feature allows the usage of the following new keywords in
47the current lexical scope:
48
49=head2 class
50
51    class NAME BLOCK
52
53    class NAME VERSION BLOCK
54
55    class NAME VERSION : ATTRIBUTES... BLOCK
56
57    class NAME;
58
59    class NAME VERSION;
60
61    class NAME VERSION : ATTRIBUTES...;
62
63The C<class> keyword declares a new package (see L<perlmod/Packages>) that is
64intended to be a class. All other keywords from the C<class> feature should be
65used within the scope of this declaration.
66
67    class WithVersion 1.000 {
68        # class definition goes here
69    }
70
71Classes can be declared in either block or statement syntax. If a block is
72used, the body of the block contains the implementation of the class. If the
73statement form is used, the remainder of the file is used up until the next
74C<class> or C<package> statement.
75
76A C<class> declaration can optionally have a version number, similar to the
77C<package> keyword. It can also optionally have attributes. If both are
78specified, the version number must come first, before the attributes.
79
80C<class> and C<package> declarations are similar, but classes automatically get
81a constructor named C<new> - you don't have to (and should not) write one.
82Additionally, in the class BLOCK you are allowed to declare fields and methods.
83
84=head2 field
85
86    field VARIABLE_NAME;
87
88    field VARIABLE_NAME = EXPR;
89
90    field VARIABLE_NAME : ATTRIBUTES;
91
92    field VARIABLE_NAME : ATTRIBUTES = EXPR;
93
94Fields are variables that are visible in the scope of the class - more
95specifically within L</method> and L<ADJUST|/Adjustment> blocks. Each class
96instance gets its own storage of fields, independent of other instances.
97
98A field behaves like a normal lexically scoped variable. It has a sigil and is
99private to the class (though creation of an accessor method will make it
100accessible from the outside). The main difference is that different instances
101access different values in the same scope.
102
103    class WithFields {
104        field $scalar = 42;
105        field @array  = qw(this is just an array);
106        field %hash   = (species => 'Martian', planet => 'Mars');
107    }
108
109Fields may optionally have initializing expressions. If present, the expression
110will be evaluated within the constructor of each object instance. During each
111evaluation, the expression can use the value of any previously-set field, as
112well as any other variables in scope.
113
114    class WithACounter {
115        my $next_count = 1;
116        field $count = $next_count++;
117    }
118
119When combined with the C<:param> field attribute, the defaulting expression can
120use any of the C<=>, C<//=> or C<||=> operators. Expressions using C<=> will
121apply whenever the caller did not pass the corresponding parameter to the
122constructor at all. Expressions using C<//=> will also apply if the caller did
123pass the parameter but the value was undefined, and expressions using C<||=>
124will apply if the value was false.
125
126During a field initializing expression, the instance is not yet constructed
127and so the C<$self> lexical is not available.  However, the special
128C<__CLASS__> token may be used to obtain the name of the class being
129constructed, for example in order to invoke class methods on it to help in
130constructing values for fields.
131
132    class WithCustomField {
133        use constant DEFAULT_X => 10;
134        field $x = __CLASS__->DEFAULT_X;
135    }
136
137This allows subclasses to override the method with different behaviour.
138
139    class DifferentCustomField :isa(WithCustomField) {
140        sub DEFAULT_X { rand > 0.5 ? 20 : 30 }
141    }
142
143When an instance of C<DifferentCustomField> is constructed, the C<__CLASS__>
144expression in the base will yield the correct class name, and so invoke this
145overridden method instead.
146
147=head2 method
148
149    method METHOD_NAME SIGNATURE BLOCK
150
151    method METHOD_NAME BLOCK
152
153    method SIGNATURE BLOCK
154
155    method BLOCK
156
157Methods are subroutines intended to be called in the context of class objects.
158
159A variable named C<$self> populated with the current object instance will
160automatically be created in the lexical scope of C<method>.
161
162Methods always act as if C<use feature 'signatures'> is in effect, but C<$self>
163will not appear in the arguments list as far as the signature is concerned.
164
165    class WithMethods {
166        field $greetings;
167
168        ADJUST {
169            $greetings = "Hello";
170        }
171
172        method greet($name = "someone") {
173            say "$greetings, $name";
174        }
175    }
176
177Just like regular subroutines, methods I<can> be anonymous:
178
179    class AnonMethodFactory {
180
181        method get_anon_method {
182            return method {
183                return 'this is an anonymous method';
184            };
185        }
186    }
187
188=head1 ATTRIBUTES
189
190Specific aspects of the keywords mentioned above are managed using
191I<attributes>. Attributes all start with a colon, and one or more of them can
192be appended after the item's name, separated by a space.
193
194=head2 Class attributes
195
196=head3 :isa
197
198Classes may inherit from B<one> superclass, by using the C<:isa> class
199attribute.
200
201    class Example::Base { ... }
202
203    class Example::Subclass :isa(Example::Base) { ... }
204
205Inherited methods are visible and may be invoked. Fields are always lexical
206and therefore not visible by inheritance.
207
208The C<:isa> attribute may request a minimum version of the base class. As with
209C<use MODULE VERSION>, if the actual version of the base class is too low,
210compilation will fail.
211
212    class Example::Subclass :isa(Example::Base 2.345) { ... }
213
214The C<:isa> attribute will attempt to C<require> the named module if it is not
215already loaded.
216
217=head2 Field attributes
218
219=head3 :param
220
221A scalar field with a C<:param> attribute will take its value from a named
222parameter passed to the constructor. By default the parameter will have the
223same name as the field (minus its leading C<$> sigil), but a different name
224can be specified in the attribute.
225
226    field $x :param;
227    field $y :param(the_y_value);
228
229If there is no defaulting expression, then the parameter is required by the
230constructor; the caller must pass it or an exception is thrown. With a
231defaulting expression this becomes optional.
232
233=head3 :reader
234
235A field with a C<:reader> attribute will generate a reader accessor method
236automatically.  The generated method will have an empty (i.e. zero-argument)
237signature, and its body will simply return the value of the field variable.
238
239    field $s :reader;
240
241    # Equivalent to
242    field $s;
243    method s () { return $s; }
244
245By default the accessor method will have the same name as the field (minus the
246leading sigil), but a different name can be specified in the attribute's value.
247
248    field $x :reader(get_x);
249
250    # Generates a method
251    method get_x () { return $x; }
252
253Reader methods can be applied to non-scalar fields. When invoked in list
254context, they yield the contents of the field; in scalar context they yield
255the count of elements, as if the field variable had been placed in scalar
256context.
257
258    field @users :reader;
259    ...
260
261    scalar $instance->users;
262
263=head2 Method attributes
264
265None yet.
266
267=head1 OBJECT LIFECYCLE
268
269=head2 Construction
270
271Each object begins its life with a constructor call. The constructor is always
272named C<new> and is invoked like a method call on the class name:
273
274    my $object = My::Class->new(%arguments);
275
276During object construction, class fields are looked up in the C<%arguments>
277hash and populated where possible.
278
279=head2 Adjustment
280
281Object adjustment is a way to run arbitrary user-defined code during object
282construction. This is done by placing code in C<ADJUST> blocks. Every time an
283object is constructed, its C<ADJUST> blocks are executed (in the order in which
284they are declared).
285
286    class WellAdjusted {
287        field $x :param;
288        ADJUST {
289            say "Hello!";
290        }
291        ADJUST {
292            say "x = $x";
293        }
294    }
295
296    my $object = WellAdjusted->new(x => 42);
297    # Output:
298    #   Hello!
299    #   x = 42
300
301C<ADJUST> blocks are syntactically similar to L<C<BEGIN> or C<INIT>
302blocks|perlmod/BEGIN, UNITCHECK, CHECK, INIT and END>, which only run once.
303However, C<ADJUST> blocks, like methods, have access to C<$self> (a lexical
304variable holding the object being constructed) as well as all object fields
305created up to that point.
306
307=head2 Lifetime
308
309After the construction phase, the object is ready to be used.
310
311Using C<blessed> (C<Scalar::Util::blessed> or C<builtin::blessed>) on the
312object will return the name of the class, while C<reftype>
313(C<Scalar::Util::reftype> or C<builtin::reftype>) will return the string
314C<'OBJECT'>.
315
316=head2 Destruction
317
318An object is destroyed when the last reference to it goes away, just as with
319other data structures in Perl.
320
321=head1 TODO
322
323This feature is still experimental and very incomplete. The following list
324gives an overview of features still to be added or changed:
325
326=over 4
327
328=item * Roles
329
330Some syntax for declaring a role (likely a C<role> keyword), and for consuming
331a role into a class (likely a C<:does()> attribute).
332
333=item * Parameters to ADJUST blocks
334
335Some syntax for declaring that an C<ADJUST> block can consume named
336parameters, which become part of the class constructor's API. This might be
337inspired by a similar plan to add named arguments to subroutine signatures.
338
339    class X {
340        ADJUST (:$alpha, :$beta = 123) {
341           ...
342        }
343    }
344
345    my $obj = X->new(alpha => 456);
346
347=item * ADJUST blocks as true blocks
348
349Currently, every ADJUST block is wrapped in its own CV (subroutine) that gets
350invoked with the full ENTERSUB overhead. It should be possible to use the same
351mechanism that makes all field initializer expressions appear within the same
352CV on ADJUST blocks as well, merging them all into a single CV per class. This
353will make it faster to invoke if a class has more than one of them.
354
355=item * More accessor generator attributes
356
357Attributes to request that other kinds of accessor methods be generated for
358fields. Likely C<:writer>.
359
360    class X {
361        field $name :writer;
362    }
363
364Equivalent to
365
366    class X {
367        field $name;
368        method set_name ($new) { $name = $new; return $self; }
369    }
370
371=item * Metaprogramming
372
373An extension of the metaprogramming API (currently proposed by
374L<PPC0022|https://github.com/Perl/PPCs/pull/25>) which adds knowledge of
375classes, methods, fields, ADJUST blocks, and other such class-related details.
376
377=item * Extension Customisation
378
379Ways in which out-of-core modules can interact with the class system,
380including an ability for them to provide new class or field attributes.
381
382=back
383
384=head1 KNOWN BUGS
385
386The following bugs have been found in the experimental C<class> feature:
387
388=over 4
389
390=item *
391
392Since Perl v5.38, inheriting from a parent class which is declared in the same
393file and which hadn't already been sealed can cause a segmentation fault.
394[L<GH #20890|https://github.com/Perl/perl5/issues/20890>]
395
396=item *
397
398Since Perl v5.38 and with the experimental C<refaliasing> feature, trying to
399replace a field variable causes a segmentation fault.
400[L<GH #20947|https://github.com/Perl/perl5/issues/20947>]
401
402=item *
403
404Since Perl v5.38, it's possible to craft a class with leaky encapsulation,
405which can cause a segmentation fault.
406[L<GH #20956|https://github.com/Perl/perl5/issues/20956>]
407
408=item *
409
410In Perl v5.38, inheriting from a class would not always attempt to load the
411parent class (fixed in Perl v5.40).
412[L<GH #21332|https://github.com/Perl/perl5/issues/21332>]
413
414=back
415
416=head1 AUTHORS
417
418Paul Evans
419
420Bartosz Jarzyna
421
422=cut
423