[TT #819] Add tests for exsec and hav opcodes
[parrot.git] / examples / tutorial / 70_class_object.pir
blobac94b68b3ec78a673f15844046d55e67aeb5eba0
1 # Copyright (C) 2007-2009, Parrot Foundation.
2 # $Id$
4 =head1 Classes
6 If we combine the ideas of namespaces, subroutines, and global variables,
7 we are well along our way to the concept of a class. Classes are
8 high-level constructs that keep data and code together into a single
9 unit.
11 A class definition in PIR consists of two parts: Creating a new class
12 PMC object, and creating the methods for that class. The class PMC
13 can be created with the C<newclass> and C<subclass> opcodes. Data fields,
14 called "attributes" can be added to the class with the C<addattribute>
15 opcode. Once a class PMC has been created, objects of that class
16 can be instantiated like normal with the c<new> opcode.
18 The functions of a class are called methods, and are created in a
19 namespace with the same name as the class. In the example below, the
20 class is called "Foo", and all the methods of that class are located
21 in C<.namespace ["Foo"]>. Methods also need to have the C<:method>
22 flag on them, to differentiate them from normal subroutines.
24 Inside a method, the C<self> keyword acts like an additional parameter
25 that contains the PMC object of the class that the method was called
26 on.
28 This example creates a class "Foo" with two attributes "bar" and "baz".
29 It also has two setter and two accessor methods, one for each attribute.
31 =cut
33 .sub main :main
34     .local pmc myclass, myobj
36     myclass = newclass 'Foo'
37     addattribute myclass, 'bar'
38     addattribute myclass, 'baz'
40     myobj = new ['Foo']
41     myobj.'set_bar'("Hello")
42     myobj.'set_baz'(5)
44     $S0 = myobj.'get_bar'()
45     say $S0
47     $I0 = myobj.'get_baz'()
48     print $I0
49     print "\n"
51 .end
54 .namespace ['Foo']
56 .sub get_bar :method
57     $P0 = getattribute self, "bar"
58     .return($P0)
59 .end
61 .sub set_bar :method
62     .param string value
64     $P0 = new ['String']
65     $P0 = value
66     setattribute self, "bar", $P0
67 .end
69 .sub get_baz :method
70     $P0 = getattribute self, "baz"
71     .return($P0)
72 .end
74 .sub set_baz :method
75     .param int value
77     $P0 = new ['Integer']
78     $P0 = value
79     setattribute self, "baz", $P0
80 .end
82 # Local Variables:
83 #   mode: pir
84 #   fill-column: 100
85 # End:
86 # vim: expandtab shiftwidth=4 ft=pir: