Документация
HTML CSS PHP PERL другое

Section 11.5.  A Few Notes About @ISA

 
Previous
Table of Contents
Next

11.5. A Few Notes About @ISA

This magical @ISA variable (pronounced "is a" not "ice-uh") declares that Cow "is a" Animal.[*] Note that it's an array, not a simple single value, because on rare occasions it makes sense to have more than one parent class searched for the missing methods. We'll show more about that later.

[*] ISA is actually a linguistic term. Once again, Larry Wall's background as a linguist has come back to influence Perl.

If Animal also had an @ISA, Perl would check there too.[Section 11.5.  A Few Notes About @ISA] Typically, each @ISA has only one element (multiple elements means multiple inheritance and multiple headaches), so we get a nice tree of inheritance.[Section 11.5.  A Few Notes About @ISA]

[Section 11.5.  A Few Notes About @ISA] The search is recursive, depth-first, and left to right in each @ISA.

[Section 11.5.  A Few Notes About @ISA] There is also inheritance through UNIVERSAL and AUTOLOAD; see the perlobj manpage for the whole story.

When we turn on use strict, we'll get complaints on @ISA because it's not a variable containing an explicit package name, nor is it a lexical (my) variable. We can't make it a lexical variable, though: it has to belong to the package to be found by the inheritance mechanism.

There are a couple of straightforward ways to handle the declaration and setting of @ISA. The easiest is to just spell out the package name:

@Cow::ISA = qw(Animal);

We can also allow it as an implicitly named package variable:

package Cow;
use vars qw(@ISA);
@ISA = qw(Animal);

If you're on a recent-enough Perl (5.6 or later), you can use the our declaration to shorten it to:

package Cow;
our @ISA = qw(Animal);

However, if you think your code might be used by people stuck with Perl 5.005 or earlier, it's best to avoid our.

If we're bringing in the class from outside, via an object-oriented module, we can change:

package Cow;
use Animal;
use vars qw(@ISA);
@ISA = qw(Animal);

to just:

package Cow;
use base qw(Animal);

That's pretty darn compact. Furthermore, use base has the advantage that it's performed at compile time, eliminating a few potential errors from setting @ISA at runtime, like some of the other solutions.


Previous
Table of Contents
Next
© 2000- NIV