Class

Classes are “template” to create objects.

Class define methods (functions) and properties (variables) of object.

Class start with ^

To access object’s assets, use dot operator.

Ex:

^Human

$name

$email

@print_info

@echo “$name – $email \n”

Then we could create object

$people_1 :(@new ^Human)

$people_1.$name: John

$people_1.$email: “[email protected]

$people_1.(@print_info)

> John – [email protected]

Constructors

Constructors usually add data to object when create a new one, you could create several using new. If you don’t create a constructor, Green Tea will create a default one. If you have more than 1 constructors, make sure they don’t have the same parameters count, since Green Tea will use parameters count to detect which constructor it used.

Ex:

^Human

$name

$email

@new $input_name, $input_email

$name, $email : $input_name, $input_email

@new $input_name

$name: $input_name

@print_info

@echo “$name – $email \n”

new ^Human, John, “[email protected]

$?.(@print_info)

> John – [email protected]

new ^Human, John

$?.(@print_info)

> John –

Access modifiers

Green Tea support private and public (default) modifier.

Private asset could not be access outside object

Ex:

^Human

$name

private $email

@new $input_name, $input_email

$name, $email : $input_name, $input_email

@new $input_name

$name: $input_name

@print_info

@echo “$name – $email \n”

@new ^Human, John, “[email protected]

$?.(@print_info)

> John – [email protected]

new ^Human, John, “[email protected]

@echo $?.$name

> John

new ^Human, John, “[email protected]

@echo $?.$email

(Error – permission denied)

Inherit

One class could inherit some other classes using operator << . When doing so, child class could add assets, overload method of the parent class. But could not remove or change type of the parent one’s assets.

With class Human above, we could have:

^Student << ^Human

$point

@print_info

@echo “$name – $email – $point \n”

$student1: (new ^Student, John, “[email protected]”)

$student1.$point: 4

$student1.(@print_info)

> John – [email protected] – 8

Static

Static assets are asset of the class, user don’t need to create object to access those static assets.

^Human

static $spicies: Homo Sapien

static @getSpicies

return $spicies

^Human.(@getSpicies)

> Homo Sapien

Convert from array to object:

An array with all keys satisfied variable’s name rules could be converted to object with no class and all public properties.

Ex:

$obj: (@to_obj [“name”=> “John”, “age”-> 24])

Generate class from no class object

An object with no class could generate a class using function @gen_class.

Ex:

^Human1 = @gen_class $obj

Now $obj belong to class ^Human1.

Leave a Reply

Your email address will not be published. Required fields are marked *