perl - Invocation of SUPER::new() -
i've seen 2 ways implement new
method in derived class.
method one:
sub new { $invocant = shift; $class = ref($invocant) || $invocant; $self = {}; bless($self, $class); $self = $self->super::new( @_ ); return($self); }
method two:
sub new { $self = shift; $class = ref($self) || $self; return $self if ref $self; $base_object = $class->super::new(@_); return bless ($base_object, $class); }
i'm not sure understand difference is. can please explain?
from comments , answers can see ref()
part bad.
but use of super::new(@_)
? in first example, hashref blessed derived class , object's super
's new
called , saved same object.
in second example on other hand, base object created class's super
s new
method , blessed new class.
what difference between these 2 ways? looks first overwrites object base object. second seems "double-bless". i'm confused.
update
you ask:
what difference between these 2 ways? looks first overwrites object base object. second seems "double-bless". i'm confused.
take heart. each of 2 methods show confused, , neither should emulated.
method 1 blesses object of class derivedclass existence , uses object call allocator/constructor of ancestorclass, replacing itself. now, ancestorclass::new uses unfortunate ref($yuck) || $yuck
idiom, means new object blessed derivedclass. so, 1 derivedclass object used construct replace it. dubious.
method 2 returns receiver ($self) if receiver object. (note ref($self)
checked twice when need checked once.) is, $o->new()
returns same $o
under method two. if receiver not object class name, is, if instead had called derivedclass->new
, ancestorclass::new called. first argument superclass' method 'derivedclass', , presumably superclass not hardcode bless
ed package name, subsequent re-blessing pointless.
just don't worry these examples. instead please consult perlobj , perlootut safe , sane uses of super.
original answer
augh, eyes!
method 1 is, daxim commented, objectionable means of allowing 1 construct object same class existing object:
my $o1 = methodone->new(); $o2 = $o1->new(); # $o2 clone of $o1. no, wait, isn't! # it's brand new, "empty" object. ha, # fooled you.
method 2 (i think) a workaround confusing practice. method 2 return very same object if new()
called.
my $o1 = methodtwo->new(); $o2 = $o1->new(); # $o2 new methodtwo. no, wait, isn't! # it's brand new object. no, wait, isn't! # it's /exactly same object/ $o1. ha, # fooled you.
don't use either. :) there may applications either of above semantics make perfect sense. wouldn't name method new()
in applications...
Comments
Post a Comment