- Perl ›
- Object Oriented ›
- Generic constructor
General - purpose constructor template
I will present a template of a general-purpose constructor. A general-purpose constructor template is a little difficult.
1. General - purpose constructor guidelines
A generic constructor should take into account not only when it is called from a class, but also when it is called from a object .
When called by the class
my $book = Book->new;
When called from an object
my $book2 = $book->new
Corresponds to both.
Another guideline is to separate the constructor and initialization process. I will create a init method for initialization .
2. Creating a generic constructor
The following is a general-purpose constructor template.
sub new { my $proto = shift; my $class = ref $proto || $proto; my $self = {}; bless $self, $class; $self->init(@_); return $self; } sub init { my ($self, @args) = @_; # Additional processing }
3. Processing to extract the class name from the object
I think this part is difficult to understand.
my $proto = shift; my $class = ref $proto || $proto;
What this does is that if $proto is an object, use ref function to retrieve the associated class name. increase.
If not, I'm trying to just use the class name. If a string (class name) is passed to ref function, a false value will be returned and the right side of || will be executed.
That's why $class will contain the class name, whether it's called by the class name or by an object.
4. Separate initialization process
The following part separates the initialization process. If you want to initialize, create the object first with the bless function. Then call the init method from that object.
It's a little confusing, but let's get used to it. To call a method of the same class, you need to call it from an object, the blessed $self.
my $self = {}; bless $self, $class; $self->init(@_);
5. Why do you need to create it this way?
It's not good yet. I'll cover it in inheritance. I'll just say that if you don't create the object this way, you'll run into trouble when trying to inherit.