Object-oriented Perl 3

xiaoxiao2021-03-06  38

Object-oriented Perl 3

How to use Instance Variabl instance variables

What is an instance variable, an instance variable is a variable associated with an instance. Example variables of different objects are different

In the namespace, it is said that there is roomlike, it is private property. Instead, she is a variable, she is public.

Speaking here, you should mention the constructor mentioned in the previous section. In all the constructors mentioned earlier, we have used one.

An anonymous Haxi as a parameter of Bless, is it a magical place in Haxse? In fact, we can Bless any one.

Ref. Scalar, Array, Hash, Sub, Typeglob. The purpose of using Haxi is that her key / value pair

Can be more convenient to express instance variables.

Let's take an example of how specifically manages instance variables.

Package Hero;

Sub new {

MY $ Class = Shift;

MY $ Self = {@_}; # Here and the previous

Bless $ SELF, $ Class;

RETURN $ SELF;

}

Sub getname {

MY $ HERO = Shift;

RETURN $ HERO -> {name};

}

-------------------------------------------------- -

Use Hero;

MY $ refhero = HERO-> New (name => "wti"); # create a hero whose is wti

Print $ refhero-> getname; # here will get wti;)

-------------------------------------------------- -

As mentioned above, the parameters for the New, when using->, actually ("Hero", Name => "WTI"), know this,

The above code is very well understood. The $ Class first took out "Hero", and the things will be in {}. at this time

$ Self is {name => "wti"}; $ self is passed to $ refhero when constructing a new Hero.

The following $ refhero-> getName; call the instance function (later), the same use ->, pass the parameter table for getName

Yes ($ refhero), to getname, $ Refhero passed to $ HERO, $ HERO is now a reference to Haxi,

His West is {name => "wti"}. This GetName finally returned to Hero's name "wti" :).

The following code is the same as the effect, as an exercise to analyze it! (Note, here reflects the strengths of Haxi,

If you use array, you have to have a good memory, remember the first few properties in arrays)

Package Hero;

Sub new {

MY $ Class = Shift;

MY $ Self = [@_]; # Here and the previous

Bless $ SELF, $ Class;

RETURN $ SELF;

}

Sub getname {

MY $ HERO = Shift;

RETURN $ HERO -> [0];

}

1;

-------------------------------------------------- -

Use Hero;

MY $ refhero = HERO-> New ("wti"); # create a hero whose name is wtiprint $ refhero-> getname; # here will get wti;)

-------------------------------------------------- -

转载请注明原文地址:https://www.9cbs.com/read-66379.html

New Post(0)