Steve Grazzini wrote:
> On Thu, Oct 23, 2003 at 06:48:29AM -0700, R. Joseph Newton wrote:
> > "Randal L. Schwartz" wrote:
> > > >>>>> "Dan" == Dan Anderson <[EMAIL PROTECTED]> writes:
> > >
> > > Dan> my $class = ref($proto) || $proto;
> > >
> > > Don't do this!
> >
> > I'm still a little mystified as to what you find offensive there.
>
> [snip]
>
> > I'll grant that I have sometimes felt silly having that construct in a root
> > class, but so far it has not done any actual damage.
>
> There are two things going on --
>
> First, the constructor is taking the classname from the first argument,
> like this:
>
> sub new {
> my $class = shift;
> my $self = { initial => 'data' };
> bless $self, $class;
> }
>
> There's nothing wrong with that, and in fact it's *necessary* if a derived
> class wants to inherit the new() method from Foo. So don't feel silly about
> using "my $class = shift" in a root class! That's where you really need to
> be using it.
>
> But the constructor is also prepared to take an object as the first argument
> instead of just the classname-as-a-string. This is explained in perltoot:
>
> While we're at it, let's make our constructor a bit more flexible.
> Rather than being uniquely a class method, we'll set it up so that it
> can be called as either a class method or an object method. That way
> you can say:
>
> $me = Person->new();
> $him = $me->new();
Okay, I just found out where I got confused. I've never read perltoot, but I
skipped over a couple paragraphs, actually a code sample and a paragraph, in
reading perlobj:
If you care about inheritance (and you should; see the section on
"Modules: Creation, Use, and Abuse" in the perlmodlib manpage), then you
want to use the two-arg form of bless so that your constructors may be
inherited:
[glossed over this:
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->initialize();
return $self;
}
Or if you expect people to call not just "CLASS->new()" but also
"$obj->new()", then use something like this. The initialize() method
used will be of whatever $class we blessed the object into:
...and connected the text above to the code sample below]
sub new {
my $this = shift;
my $class = ref($this) || $this;
my $self = {};
bless $self, $class;
$self->initialize();
return $self;
}
I must say that it makes much more sense reading this way. The construct is now
much less mysterious, too.
Thanks,
Joseph
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]