1 # Copyright (C) 2007-2009, Parrot Foundation.
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
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
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.
34 .local pmc myclass, myobj
36 myclass = newclass 'Foo'
37 addattribute myclass, 'bar'
38 addattribute myclass, 'baz'
41 myobj.'set_bar'("Hello")
44 $S0 = myobj.'get_bar'()
47 $I0 = myobj.'get_baz'()
57 $P0 = getattribute self, "bar"
66 setattribute self, "bar", $P0
70 $P0 = getattribute self, "baz"
79 setattribute self, "baz", $P0
86 # vim: expandtab shiftwidth=4 ft=pir: