13.10.3. Discussion
Imagine you've implemented a class named Person that supplies a
constructor named new, and methods such as
age and name. Here's the
straightforward implementation:
package Person;
sub new {
my $class = shift;
my $self = { };
return bless $self, $class;
}
sub name {
my $self = shift;
$self->{NAME} = shift if @_;
return $self->{NAME};
}
sub age {
my $self = shift;
$self->{AGE} = shift if @_;
return $self->{AGE};
}
You might use the class in this way:
use Person;
my $dude = Person->new( );
$dude->name("Jason");
$dude->age(23);
printf "%s is age %d.\n", $dude->name, $dude->age;
Now consider another class, the one named Employee:
package Employee;
use Person;
@ISA = ("Person");
1;
There's not a lot to that one. All it's doing is loading in class
Person and stating that Employee will inherit any needed methods from
Person. Since Employee has no methods of its own, it will get all of
its methods from Person. We rely upon an Employee to behave just like
a Person.
use Employee;
my $empl = Employee->new( );
$empl->name("Jason");
$empl->age(23);
printf "%s is age %d.\n", $empl->name, $empl->age;
By proper design, we mean using only the two-argument form of
bless, avoiding any direct access of class data,
and exporting nothing. In the Person::new( )
function defined previously, we were careful to do these things. We
use some package data in the constructor, but the reference to this
is stored on the object itself. Other methods access package data via
that reference, so we should be okay.
you'd have a subtle problem, because the function wouldn't get an
argument of "Person" as it is expecting, and so it couldn't bless
into the passed-in class. Still worse, you'd probably want to try to
call Employee::new also. But there is no such
function! It's just an inherited method.
So, don't call a function when you mean to invoke a method.