Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using __PACKAGE__ inside my methods bad for inheritance?

Tags:

oop

perl

If inside my code I'll have calls like:

__PACKAGE__->method;

will this limit the usability of this module, if this module is inherited?

like image 234
Geo Avatar asked Nov 30 '09 13:11

Geo


3 Answers

It depends on what you want to do:

#!/usr/bin/perl

package A;

use strict; use warnings;

sub new { bless {} => $_[0] }

sub method1 {
    printf "Hello from: %s\n", __PACKAGE__;
}

sub method2 {
    my $self = shift;
    printf "Hello from: %s\n", ref($self);
}

package B;

use strict; use warnings;
use parent 'A';

package main;

my $b = B->new;

$b->method1;
$b->method2;

Output:

Hello from: A
Hello from: B
like image 198
Sinan Ünür Avatar answered Nov 11 '22 00:11

Sinan Ünür


If you intend to inherit that method, call it on the referent and don't rely on the package you find it in. If you intend to call a method internal to the package that no other package should be able to see, then it might be okay. There's a fuller explanation in Intermediate Perl, and probably in perlboot (which is an extract of the book).

In general, I try not to ever use __PACKAGE__ unless I'm writing a modulino.

Why are you trying to use __PACKAGE__?

like image 44
brian d foy Avatar answered Nov 11 '22 01:11

brian d foy


That depends. Sometimes __PACKAGE__->method() is exactly what you need.

Otherwise it's better to use ref($self)->class_method() or $self->method().

like image 3
Peter Stuifzand Avatar answered Nov 11 '22 00:11

Peter Stuifzand