|Do you know where your variables are?|
Re: Perl Inheritance & module variablesby brian_d_foy (Abbot)
|on Sep 20, 2008 at 19:41 UTC||Need Help??|
You're really asking how to write accessor methods. You call a method and you get the value of some property. You want to write methods that ask the question you want answered.
Here are two class, Parent and Child. The Child class inherits from Parent. Inside each class there is a VERSION method that returns the value of the $VERSION in that package. In neither case is $VERSION part of the object. They are class data.
Those VERSION methods take care of answering the version question for each package as long as I call them directly as class methods:
But now I want to do that from a Child object. That's where the child_version and parent_version methods come in. Once I have the $child object, in parent_version I can get its parent version by calling its SUPER class. The SUPER is a virtual class that is the parent class of the one it is compiled in (Child in this case).
The VERSION and parent_version methods in Child take care of most everything you need. Where you're getting confused, I think, is how the Parent fits in to this. More on that in a moment. You can add a child_version method to Parent. It just takes the first thing on the argument list and calls VERSION on it. When I call child_version on the $child object, Perl doesn't find the child_version in Child so it looks in its superclass and finds it in Parent:
However, one of the points of inheritance is that you shouldn't need this two-way communication. You don't think about the parent class having part of it and the child class having another part. In this case, the child_version method is just the same thing as Child's VERSION:
In Parent's child_version, it takes the first thing on the argument list, which is the $child object. That's how Parent accesses anything it needs to know in Child: just ask the child object that you got as the first argument.
brian d foy <email@example.com>
Subscribe to The Perl Review