Initializing Objects
There are two ways to set the initial values of object fields.
- Pass in a Map of values to the initializer
- Set values inside the
onCreate
method
Initializer Map
When you pass a Map of values to the initializer, it will set any public
fields that match.
class Character { public fields { name: '' health: 33 location: 'Northoros' } } // Another file //---------------------------------- // Set new values for 'health' and 'name' $char = Character({ name: 'Thatia' health: 99 }) $char.name //= 'Thatia' $char.health //= 99 $char.location //= 'Northoros'
onCreate Method
You can define a method named onCreate
, which is like __construct
in PHP.
This 'hook' method will be called automatically after the object is created, and after the fields
are initialized.
The first and only argument to this method will contain the Map passed to the initializer, or an empty Map if one was not passed in.
class Character { public fields { weapon: 'Fist' } fun onCreate($init) { if $init['isArcher'] { @.weapon = 'Bow & Arrow' } } } // Another file //---------------------------------- $char = Character({ isArcher: true }) $char.weapon //= 'Bow & Arrow'